javascript - 排除 child 的 jQuery 监听器

标签 javascript jquery actionlistener

我有一个 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/

相关文章:

javascript - 切换单个表同时隐藏其他表

java - actionListener/actionhandler 的问题 java NullPointerException

javascript - “订阅”已弃用。使用观察者而不是完整的回调

javascript - 从 DOM 节点中提取纯文本

javascript - 鼠标悬停时内容淡入,鼠标移出时隐藏

Java GUI JButton 到 Action 监听器

java - 有人能告诉我为什么我的 actionListener for 循环不起作用吗?

javascript - innerHTML 和 FireFox 兼容性吗?

javascript - 在 JavaScript 中构建一个对象,该对象由 HTML 表格行中单元格的名称/值对组成

jquery函数有字符串参数来访问对象