JQuery 绑定到对象单击上的文档单击处理程序会立即触发文档单击处理程序
我编写了一个单击处理程序,它创建了到文档单击处理程序的绑定,如下所示:
$("#button").bind('click',function(){
....
$(document).bind('click',function(){
console.log("document.click");
});
});
我发现奇怪的是文档单击处理程序触发,并且我立即获得控制台日志。换句话说,我第一次单击#button 时就会收到控制台日志。这是因为单击冒泡到文档需要时间,并且我在文档单击事件到达那里之前绑定到文档单击事件吗?有什么办法可以防止这种情况发生吗?
I wrote a click handler that creates a binding to the document click handler like so:
$("#button").bind('click',function(){
....
$(document).bind('click',function(){
console.log("document.click");
});
});
What I find strange about this is that the document click handler fires and I get the console log immediately. In other words, I get the console log the very first time I click #button. Is this because it takes time for the click to bubble up to the document, and I'm binding to the document click event just before it gets there? Is there any way to prevent this from happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
这将防止事件冒泡
try this:
This will prevent the event from bubbling up