何时调用“DOMNodeInserted”事件?

时间:2011-11-26 09:30:47

标签: javascript dom javascript-events dom-events dom-node

当节点“被追加到”或“被追加”时,会调用

DOMNodeInserted事件?

我问这个是因为以下代码:

function AddTextToContainer () {
    var textNode = document.createTextNode ("My text");
    var container = document.getElementById ("container");

    if (container.addEventListener) {
        container.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
    }
    container.appendChild (textNode);
}

那:

function AddTextToContainer () {
   var textNode = document.createTextNode ("My text");
   var container = document.getElementById ("container");

   if (textNode.addEventListener) {
       textNode.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
   }
   container.appendChild (textNode);
}

两者在Chrome中调用OnNodeInserted。这是一个错误吗?

2 个答案:

答案 0 :(得分:9)

这是W3C

DOMNodeInserted
Fired when a node has been added as a child of another node. 
This event is dispatched after the insertion has taken place. 
The target of this event is the node being inserted.
Bubbles: Yes
Cancelable: No
Context Info: relatedNode holds the parent node

关键是 Bubbles:是 - 这就是为什么它也会在容器上被解雇。

答案 1 :(得分:-1)

如果你想阻止事件冒泡,只需使用event.stopPropagation();在您的文本节点回调中。然后事件不再在dom树上处理。