2011-11-26 84 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