Javascript活动,捕捉作品泡泡不会 [英] Javascript Events, Capturing works Bubbling doesn't
问题描述
< HTML>
< body>
< div id =textbox>
还没有
< / div>
< / body>
< script>
//通过update事件增加
var val = 0;
//事件从这里开始
textbox = document.getElementById(textbox);
textbox.addEventListener(update,function(e){
textbox.innerHTML = val;
},false);
//应该在这里发泡
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>
在我的这里的代码里面有一个div文本框。我认为发送到文本框的更新事件应该向身体冒泡,但不会。计数器从不更新。
如果我将body的事件侦听器的UseCapture参数设置为true,则计数器将更新。
dispatchEvent
调度你的事件。 总结,这意味着
当事件是派发到
参与 tree (例如元素),可以达到
事件侦听器,该对象的祖先也。
首先所有对象的 ancestor 捕获变量设置为true的事件侦听器 =nofollow>事件监听器,在树顺序。
第二,对象自己的事件侦听器。
最后,只有事件的 bubbles 属性值为
true,对象的祖先 事件侦听器再次被调用,
但现在反向树顺序。
因此,如果气泡
属性不正确,事件不会起泡。
您可以设置气泡
当您使用事件
创建事件时,属性为true:
code> 事件 =新的事件( type [, eventInitDict ])
type 的新的事件 / code>
属性值设置为
类型。可选的 eventInitDict 参数允许设置bubbles
和cancelable
属性通过对象成员
同名。
My understanding of JS event propagation is that an event first "captures" down the DOM tree, then "bubbles" back up, triggering handlers along the way.
<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>
In my code here there is a div "textbox" inside the body. I think the update event sent to the textbox should bubble up to the body, but it doesn't. The counter never updates.
If I set the UseCapture argument of the body's event listener to true, the counter updates.
Why does capturing work, but not bubbling?
dispatchEvent
dispatches your event. Summarizing, that means
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.
Therefore, if the bubbles
attribute is not true, the event won't bubble.
You can set the bubbles
attribute to true when you create the event with Event
:
event = new Event(type [, eventInitDict])
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活动,捕捉作品泡泡不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!