2011-11-26 83 views
5

DOMNodeInserted当节点“被附加到”或“附加”时调用事件?何时调用“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中。这是一个错误吗?

回答

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 

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

-1

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

+0

'event.stopPropagation()'似乎对我没有任何影响。该活动仍在为目标儿童开枪。我通过检查'event.target'是我认为是的对象来解决它。 – devios1