简体   繁体   中英

How to prevent click event from outer div if inner div is clicked

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?

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.net/4L87qLte/

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM