我有一个 dd 项目的 dl 列表。每个 dd 项都附加了一个监听器(见下文),因此如果单击它,我可以重建页面并更改一些内容。这些 dd 项目中的每一个都有一个复选框,我希望通过该复选框将其排除在该监听器之外(因此它可以被另一个监听器拾取)。
出现的问题是,每当我单击 dd 中的任何位置时,它都会应用 dd 监听器,而不是复选框监听器,即使我单击了复选框也是如此。有没有办法在不在 dd 中设置 div 并单独应用监听器的情况下区分究竟点击了什么?
示例 HTML 代码:
<dl>
<dd class="class1 class2 class3">Some text and stuff
<input type="checkbox" class="class1 checkBox">
</dd>
</dl>
示例 jQuery 代码:
$("class1.checkbox").live("click", function() {
//Do some other, completely different, cool stuff
//console.log($(this).parent().attr("id"));
console.log("test");
});
$("dd.class1.class2").live("click", function () {
//Do some cool stuff
});
最佳答案
您需要停止事件冒泡。
$(".class1:checkbox").click(function(e) {
alert('clicked checkbox');
e.stopPropagation();
});
$("dd.class1.class2").click(function () {
alert('clicked dd');
});
http://api.jquery.com/event.stopPropagation/
“向上冒泡”的概念就好比如果你有一个带有点击事件的子元素,你不希望它触发父元素的点击事件。您可以使用 event.stopPropagation()
。
event.stopPropagation()
基本上表示仅将此点击事件应用于此子节点并且不告诉父容器任何内容,因为我不希望它们使用react。
事件捕获:
| |
---------------| |-----------------
| element1 | | |
| -----------| |----------- |
| |element2 \ / | |
| ------------------------- |
| Event CAPTURING |
-----------------------------------
事件冒泡:
/ \
---------------| |-----------------
| element1 | | |
| -----------| |----------- |
| |element2 | | | |
| ------------------------- |
| Event BUBBLING |
-----------------------------------
如果您正在使用 live()
或 delegate()
,您将需要return false;
,尽管它可能不起作用。阅读下面的引述。
根据 JQuery docs :
Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.
一个很好的资源:http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
关于javascript - 排除 child 的 jQuery 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7127474/