我对 JS 事件传播的理解是,事件首先“捕获”DOM 树,然后“冒泡”备份,沿途触发处理程序。
<html>
<body>
<div id="textbox">
nothing yet
</div>
</body>
<script>
// Gets incremented by "update" event
var val = 0;
// Event starts here
textbox = document.getElementById("textbox");
textbox.addEventListener("update", function(e) {
textbox.innerHTML = val;
}, false);
// Should bubble here
body = document.getElementsByTagName("body")[0];
body.addEventListener("update", function(e) {
val++;
}, false);
function update() {
var e = new Event("update");
textbox.dispatchEvent(e);
}
setInterval(update, 10);
</script>
</html>
在我的code here正文内有一个 div“文本框”。我认为发送到文本框的更新事件应该冒泡到正文,但事实并非如此。计数器永远不会更新。
如果我将正文事件监听器的 UseCapture 参数设置为 true,计数器会更新。
为什么捕获有效,但不冒泡?
最佳答案
dispatchEvent
dispatches你的事件。 Summarizing , 这意味着
When an event is dispatched to an object that participates in a tree (e.g. an element), it can reach event listeners on that object's ancestors too.
First all object's ancestor event listeners whose capture variable is set to true are invoked, in tree order.
Second, object's own event listeners are invoked.
And finally, and only if event's bubbles attribute value is true, object's ancestor event listeners are invoked again, but now in reverse tree order.
因此,如果 bubbles
属性不为真,则事件不会冒泡。
当您使用 Event
创建事件时,您可以将 bubbles
属性设置为 true:
<i>event</i> = new <a href="http://www.w3.org/TR/dom/#concept-event-constructor" rel="noreferrer noopener nofollow">Event</a>(<i>type</i> [, <i>eventInitDict</i>])
Returns a new event whose
type
attribute value is set to type. The optional eventInitDict argument allows for setting thebubbles
andcancelable
attributes via object members of the same name.
关于Javascript 事件,捕获作品冒泡不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31818984/