admin管理员组

文章数量:1296240

I have 2 divs with a js click event. One div is located in the other one.

But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?

I have 2 divs with a js click event. One div is located in the other one.

But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?

Share Improve this question asked Apr 26, 2016 at 15:01 dunnohowishouldnamemyselfdunnohowishouldnamemyself 1592 silver badges12 bronze badges 1
  • 1 Possible duplicate of Prevent execution of parent event handler – Nirpendra Patel Commented Apr 26, 2016 at 15:07
Add a ment  | 

3 Answers 3

Reset to default 5

By default, event handling starts at the lowest level of the DOM where you have defined a handler to handle the target event. Assuming you have defined event listeners higher in the parent chain to handle the same event, you will need to stop the propagation of the event if you do not wish for the event to be handled beyond the layer you intend for it to be handled in:

e.stopPropagation();

See what happens when you remove that line in the example below:

document.querySelector('.inner').addEventListener('click', function(e) {
  alert('inner div clicked!');
  e.stopPropagation();
});

document.querySelector('.outer').addEventListener('click', function() {
  alert('outer div clicked!');
});
.outer {
  width: 200px;
  height: 200px;
  background: blue;
}

.inner {
  width: 100px;
  height: 100px;
  background: green;
}
<div class='outer'>
  Outer
  <div class='inner'>
    Inner
  </div>
</div>

Use event.stopPropagation();

Like this

document.getElementById("#seconddiv").addEventListener("click", function($event){
    $event.stopPropagation();
});

Use event.stopPropagation:

document.getElementById('inner').addEventListener('click', function (event){
    event.stopPropagation();
    console.log ('Inner div clicked!');
});

https://jsfiddle/4L87qLte/

本文标签: javascriptHow to prevent click event from outer div if inner div is clickedStack Overflow