代码:
scope.offCanvasShow = function ($event) {
$('.app-off-canvas-menu').toggleClass('show');
// Prevents default functionality of a element
// In this instance, this prevents the anchor from reloading the page on click.
$event.preventDefault();
$event.stopPropagation();
$(document).one('touchstart click', offCanvasHandler);
/**
* Checks to see if the event target isn't .off-canvas-menu or has off-canvas-menu as a parent then removes the
* show class.
* @param event - is the event of the function
*/
function offCanvasHandler(event) {
console.log('hello');
if (!$(event.target).closest('.app-off-canvas-menu').length) {
$('.app-off-canvas-menu').removeClass('show');
$(document).off('touchstart click', offCanvasHandler);
} else {
$(document).one('touchstart click', offCanvasHandler);
}
}
};这是一个简单的画布下拉菜单。我有个奇怪的冒泡问题。我以为我修正了.one()函数。
如果你点击类应用程序-画布菜单几次,然后保持菜单打开,然后点击菜单外面的菜单关闭,这就是我想要的。
但是,当我在菜单外单击时,控制台日志似乎会多次运行,这取决于我点击了应用程序的次数--画布菜单上的汉堡包。
有人能从我的代码中看到明显的东西吗?
值得注意的是,我使用的角度,所以它可能是可能的,我必须采取不同的方式。
发布于 2016-02-01 09:33:42
如果你点击类应用程序-画布菜单几次,然后保持菜单打开,然后点击菜单外面的菜单关闭,这就是我想要的。
每次单击该类时,都会绑定另一个处理程序:
$(document).one('touchstart click', offCanvasHandler);因此,当您单击元素外部时,它将执行所有这些处理程序。
来自jQuery网站:
.one()方法与.on()完全相同,只不过在第一次调用之后处理程序是不绑定的。
所以你不用绑定它一次,它只运行一次。这可能会引起混乱。
用代码更新:
var isBound = false;
scope.offCanvasShow = function ($event) {
$('.app-off-canvas-menu').toggleClass('show');
// Prevents default functionality of a element
// In this instance, this prevents the anchor from reloading the page on click.
$event.preventDefault();
$event.stopPropagation();
if(!isBound) {
$(document).one('touchstart click', offCanvasHandler);
isBound = true;
}
/**
* Checks to see if the event target isn't .off-canvas-menu or has off-canvas-menu as a parent then removes the
* show class.
* @param event - is the event of the function
*/
function offCanvasHandler(event) {
console.log('hello');
if (!$(event.target).closest('.app-off-canvas-menu').length) {
$('.app-off-canvas-menu').removeClass('show');
$(document).off('touchstart click', offCanvasHandler);
} else {
$(document).one('touchstart click', offCanvasHandler);
}
}
};https://stackoverflow.com/questions/35126977
复制相似问题