How to prevent children click on parent click

2019-09-16 12:23发布

问题:

I have done the following code structure and doing addClass item_box_popup and removeClass item_box on click of item_box div.

<div class="item_box"> <!--This is the small div which when clicked changes to the item_box_popup div-->
  <div class="name">...</div>
  <div class="detail">...</div>
</div>

<div class="item_box_popup"> <!--This div expands to show the detail and the children in it has a click event-->
  <div class="name">...</div>
  <div class="detail">...</div>
</div>

The item_box div has a click event in it and not the children. The working is to change the div to item_box_pop div by addClass and removeClass when clicked.

The item_box_popup does not have a click event but the children has the click event defined. We have used delegate to define the click event for .item_box_popup .name etc.

The problem is when we click the item_box div the click event defined for .item_box_popup .name is also getting triggered. This may be due to the change class defined on click for .item_box.

I don't want the click event to trigger on the children when .item_box is clicked. I have tried undelegate to stop triggering of click on item_box children and just do the change class defined in the click for it but this is not working.

The click event for .item_box

$('.slide > div').bind('click',function(e) {
    if(!$(this).hasClass('item_box_popup')){
        var index=$('.slide > div').index(this);
            $(this).removeClass('item_box');
            $(this).addClass('item_box_popup');     
        Nomad.config.firstVisibleItem=index;<!--This is to set the position for .item_box_popup-->              
    }           
});

The click event for .item_box_popup

$("body").delegate('.item_box_popup .name, .item_box_popup .detail','click', function(e){
  //working code here for this
});

e.stopPropagation(); disables the default click handler of .item_box

回答1:

Try adding event.preventDefault(); after the call that you do want to happen, it stops the default action from happening e.g. the default action of an a element.

I can't say exactly where to try the call or whether it will solve your problem without seeing your js code though. The html isn't where your problem is, its the js code, so if this (or the other answer that posted while I was typing this!) doesn't work can you edit your post to include your js, please?

Update:

I've copied your code into JSFiddle and added an e.stopPropagation() call to the item_box click handler, and it works as I expected: http://jsfiddle.net/chkaQ/2/

When you click on an item_box child div, it changes it to an item_box_popup and doesn't execute the item_box_popup child click event... have I got it wrong, or is that not what you want it to do?



回答2:

You need to prevent the event from 'bubbling' up to the parent using stopPropagation: http://api.jquery.com/event.stopPropagation/



标签: jquery click