如何从点击事件中分配子元素

时间:2009-05-19 13:35:18

标签: javascript jquery

有人可以帮我这个吗?有HTML代码:

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

我想通过点击 h3 标记切换 p 元素,但如果点击标签<我不想切换/强>

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

2 个答案:

答案 0 :(得分:17)

您需要检查操作的目标

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

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

答案 1 :(得分:2)

你想停止传播()

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