有没有办法查明 jquery 事件是否已被另一个事件监听器捕获?
以下示例:我有以下事件绑定(bind):
$("body").on("click", ".linkarea", function (e) {
document.location.href = $(this).find("a")a.attr("href");
});
$("body").on("click", ".delete", function (e) {
console.log("DELETE");
});
这就是我的 HTML 的样子:
<div class="linkarea">
<h1><a href="/test.html">LINKED</a></h1>
<p>Blabla</p>
<a class="btn delete">DELETE</a>
</div>
我想要实现的是,如果用户单击 div 的任何部分(除了 .delete 按钮),他应该被重定向到/test.html。如果他单击 .delete 按钮,则只应执行(!)其他事件代码。
我知道,我可以将“e.stopPropagation()”添加到删除事件中,但也许我在另一个地方使用 .delete 类,并且可能有必要它会冒泡。我正在寻找的是这样的:
$("body").on("click", ".linkarea", function (e) {
if(!e.wasAlreadyExecuted)
document.location.href = $(this).find("a")a.attr("href");
});
最佳答案
您可以将 event.target
过滤掉:
$("body").on("click", ".linkarea", function (e) {
if($(e.target).closest('.delete').length) return;
document.location.href = $(this).find("a")a.attr("href");
});
编辑:
I know, that I could add "e.stopPropagation()" to the delete-event, but maybe I use the .delete class on another place, and there it could be necessary, that it bubbles.
或者停止来自 .delete
的事件传播点击处理程序:
$("body").on("click", ".delete", function (e) {
console.log("DELETE");
e.stopPropagation();
});
罢工><罢工>罢工>
关于javascript - jQuery,只触发事件,如果没有触发其他事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424882/