如何阻止父点击事件更改复选框

时间:2017-11-17 09:56:37

标签: javascript jquery html checkbox

我在父容器中有一个复选框,它有一个click事件,每当我尝试单击复选框时,父点击首先工作,然后是更改事件,我在父事件和子事件上使用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 个答案:

答案 0 :(得分:5)

您必须在复选框上绑定click事件,而不是change事件:http://jsfiddle.net/ohc8jt6w/

答案 1 :(得分:1)

事件的顺序很重要,首先发生点击事件,然后更改下一个事件,所以在您的情况下,您需要将事件处理的类型更改为Click click here 查看点击复选框后发生的事件的顺序/优先级

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

答案 2 :(得分:-2)

这是因为e.stopPropagation();处于change事件,.child处于点击事件。您可以像在@rikpg示例中那样执行此操作,但是如果您需要更改事件,则只需将新click event添加到只有stopPropagation的复选框

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