[英]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. 假设有
div
块,该块内有许多元素,它们将引发许多事件。 I don't want those events continuing bubble up, or listeners outside the div
block may process wrong events with the same names. 我不希望这些事件继续冒泡,否则
div
块之外的侦听器可能会处理具有相同名称的错误事件。 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. 您必须分别监听每个事件,并使用
e.stopPropagation()
停止传播,其中e
是事件对象。 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. 正确处理冒泡事件的最常见方法是验证目标元素(
e.target
)并相应地忽略。
For exemple, you could check if e.target === e.currentTarget
to know if the event came from a child or not. 例如,您可以检查
e.target === e.currentTarget
以了解事件是否来自孩子。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.