如何防止更改复选框时触发父级点击事件

4

我有一个复选框在父容器内,父容器有一个点击事件。每当我尝试点击复选框时,父容器的点击事件会先触发,接着是复选框的改变事件。我在父子事件中都使用了e.stopPropagation();,但仍然无效。

// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});

Fiddle example

3个回答

8

1
事件的顺序很重要,点击事件先发生,然后是更改事件。因此,在您的情况下,您需要将事件处理类型更改为Click单击此处以查看在单击复选框后发生的事件序列/优先级。
$('.hello').on('click change', function(e){
e.stopPropagation(); 
 alert('checkbox '+e.type);
});

-1
这是因为 e.stopPropagation();change 事件上,而 .child 有 click 事件。你可以像 @rikpg 的例子一样做到这一点,但如果你需要 change 事件,你应该只给复选框添加一个新的 click 事件,它只有 stopPropagation

http://jsfiddle.net/wppv2152/2/


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