如何确保绑定到 hashChange 事件不会冒泡?
我试图阻止我的 hashChange 事件绑定冒泡。
我有这个:
$(window).bind('hashchange', function( e ) {
console.log("hash fired");
// run hashChange routine
});
我的脚本管理页面上的面板,每个面板都有自己的历史堆栈。上面的内容在每次转换时都会触发,但我在向前转换时阻止了 hashChange,因此我可以更深入地导航到面板中。在向后“转换”时,只有 hashChange 触发并且不会被阻止,因此我可以返回。
导航可能如下所示:
panel A, start down > page2
panel A, page2 down > page3
panel A, page3 up > page2
panel A, page2 up > start - hashChange fires twice here...
一切正常(= hashChange 触发一次),直到我到达初始设置之前的页面。在最后一步,上面的 hashChange 绑定会触发两次。我一直尝试在某处设置一个标志来阻止第二个 hashChange,但它并没有像我希望的那样工作。
问题:
如何保证不冒泡呢?我正在尝试这样的事情,但它不起作用:
var $blockBubblingHashes = 0;
$(window).bind('hashchange', function( e ) {
if ($blockBubblingHashes == 0) {
// run hashChange routine
$blockBubblingHashes = 1;
} else {
$blockBubblingHashes = 0;
}
});
I'm trying to keep my hashChange event binding from bubbling.
I have this:
$(window).bind('hashchange', function( e ) {
console.log("hash fired");
// run hashChange routine
});
My script manages panels on a page with each panel having it's own history-stack. The above fires with every transition, but I'm blocking the hashChange on forward transitions, so I can navigate deeper into the panel. On backwards "transitions", only hashChange fires and is not blocked, so I can go back up.
A navigation might look like this:
panel A, start down > page2
panel A, page2 down > page3
panel A, page3 up > page2
panel A, page2 up > start - hashChange fires twice here...
All works well (= hashChange fires once), until I reach the page before initial setup. On the final step the above hashChange-binding fires twice. I have tried forever to set a flag somewhere to block the 2nd hashChange, but it doesn't work as I had hoped.
Question:
How can ensure this does not bubble? I'm trying something like this, but it's not working:
var $blockBubblingHashes = 0;
$(window).bind('hashchange', function( e ) {
if ($blockBubblingHashes == 0) {
// run hashChange routine
$blockBubblingHashes = 1;
} else {
$blockBubblingHashes = 0;
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望事件处理程序仅触发一次,则应考虑使用
one()
< /a> 函数,它在第一次执行后删除处理程序。如果您特别想停止事件冒泡,而不是删除处理程序,您应该查看
stopPropagation ()
和stopImmediatePropagation()
事件对象的方法。不幸的是,我的印象是您将所有hashchange
处理程序绑定到window
,并且 jQuery 没有记录绑定到同一元素的事件处理程序的执行顺序;因此您将没有可靠的方法来知道首先调用哪个处理程序。If you want the event handler to fire only once, you should consider using the
one()
function, which removes the handler after it's first execution.If you specifically want to stop the event bubbling, rather than removing the handler, you should checkout the
stopPropagation()
andstopImmediatePropagation()
on methods the event object. Unfortunately, I get the impression you're binding all yourhashchange
handlers to thewindow
, and jQuery does not document in which order event handlers bound to the same element are executed; so you'll have no reliable way of knowing which handler is invoked first.