最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how prevent the parent click event on change a checkbox - Stack Overflow

programmeradmin1浏览0评论

I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

// 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

I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

// 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

Share Improve this question asked Nov 17, 2017 at 9:56 Jothi KannanJothi Kannan 3,3586 gold badges43 silver badges81 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

You have to bind the click event on the checkbox and not the change event: http://jsfiddle/ohc8jt6w/

Sequence of the event matters , where the click event occurs first and Change event the next ,So in your case you need to change the type of event handling to Click click here to see the sequence / priority of events happening after clicking on check box

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

This happens because e.stopPropagation(); is on change event and .child has click event. You can do this like in @rikpg example, but if you need change event, you should just add new one click event to checkbox that only has stopPropagation

http://jsfiddle/wppv2152/2/

发布评论

评论列表(0)

  1. 暂无评论