如何在点击事件中排除子元素

4

有人能帮我解决这个问题吗?以下是HTML代码:

<h3>
    <label>
        <input type="checkbox" name="country" value="us" /> United States
    </label>
</h3>
<p>Some content goes here</p>

我希望能够通过点击

标签来切换

元素,但如果我点击

$('h3').click(function() {
   // Does something goes here?
   $(this).next('p').toggle();
}


为什么不呢?难道不是p标签中的内容与您正在切换的复选框相关联的想法吗? - cgp
我假设"label"指的是实际的文本,而不是HTML元素。 - tvanfosson
(复选框由标签切换) - cgp
2个回答

17

你需要检查操作的目标。

$('h3').click(function(e) {
   // if they clicked the h3 only
   if (this == e.target) {
     $(this).next('p').toggle();
   }
}

altCognito的建议也可以,但代码更多。


2
你想要停止事件传播,可以使用 stopPropagation() 方法。
$('h3').click(function() {
   // Does something goes here?
   $(this).next('p').toggle();
}
$('label').click(function(e) {
   e.stopPropagation();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接