admin管理员组

文章数量:1323157

Let's say I have the following Code:

<div id="parent">
    <div id="child"></div>
</div>

Now I attach an onClick event to the parent div:

$('#parent').click(function() { ... });

Is there an easy way to stop the event from triggering when I click on the child div? I don't want to do something like

$('#child').click(function() { return false; });

because the child div could contain links...

Thanks!

Let's say I have the following Code:

<div id="parent">
    <div id="child"></div>
</div>

Now I attach an onClick event to the parent div:

$('#parent').click(function() { ... });

Is there an easy way to stop the event from triggering when I click on the child div? I don't want to do something like

$('#child').click(function() { return false; });

because the child div could contain links...

Thanks!

Share asked Sep 7, 2009 at 15:18 janoliverjanoliver 7,82414 gold badges62 silver badges105 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Check the event target.

The following code is untested.

var div = document.getElementById('parent');
jQuery(div).click(function(event) {
  if (event.target !== div) {
    return false;
  }
});

stopPropagation

$('#child').click(function(event) { 
       event.stopPropagation();
       //...
});

本文标签: javascriptclick event on a div should not be triggered by it39s childrenStack Overflow