5

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);
}

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

4

2 回答 2

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

关键是气泡:是的- 这就是为什么它也会在容器上发射。

于 2011-11-26T10:42:12.557 回答
-1

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

于 2011-11-26T11:26:04.910 回答