Javascript 如何防止更改复选框时的父单击事件
我在一个父容器中有一个复选框,该容器有一个单击事件,每当我尝试单击该复选框时,首先单击父单击有效,然后单击更改事件,我使用的是Javascript 如何防止更改复选框时的父单击事件,javascript,jquery,html,checkbox,Javascript,Jquery,Html,Checkbox,我在一个父容器中有一个复选框,该容器有一个单击事件,每当我尝试单击该复选框时,首先单击父单击有效,然后单击更改事件,我使用的是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 .pare
e.stopPropagation()对父事件和子事件都执行code>操作,但仍然不起作用
// 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');
});
您必须绑定复选框上的单击事件,而不是更改事件:发生这种情况是因为e.stopPropagation()代码>处于change
事件中,并且子项
具有单击事件。您可以像在@rikpg示例中那样执行此操作,但如果您需要更改事件,则只需将新的单击事件
添加到只有停止播放
事件的顺序很重要,单击事件首先发生,然后更改事件,因此在您的情况下,您需要将事件处理类型更改为单击,以查看单击复选框后事件发生的顺序/优先级
$('.hello').on('click change', function(e){
e.stopPropagation();
alert('checkbox '+e.type);
});