简体   繁体   中英

How to stop all events one html element can listen to?

Assume that there is div block, inside that block are many elements and they will fire many events. I don't want those events continuing bubble up, or listeners outside the div block may process wrong events with the same names. Can I make this without listening to bunch of events and stop them one by one?

You must listen to every events individually and stop their propagation using e.stopPropagation() , where e is the event object. There's no way to listen to every events at once and unless you have a very specific subset of events, I wouldn't take this approach.

The most common way to handle bubbling events correctly is to validate the target element ( e.target ) and ignore accordingly.

For exemple, you could check if e.target === e.currentTarget to know if the event came from a child or not.

 var logEl = document.getElementById('log'); document.getElementById('parent').addEventListener('click', function (e) { log('event comes from child? ' + (e.target !== e.currentTarget)); }); function log(msg) { logEl.appendChild(document.createElement('br')); logEl.appendChild(document.createTextNode(msg)); } 
 #parent, #parent > div { padding: 20px; border: 1px solid red; } #parent { height: 100px; width: 200px; } 
 Click inside the boxes <div id="parent"> parent <div>child</div> </div> <div id="log"></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