当子dom节点被附加到某个父节点时,是否可以监视或以某种方式检测?

时间:2015-07-12 18:11:33

标签: javascript dom

假设我有一个子节点 > t.root.left.data 0 > t.root.right.data 12 ,如果我不知道父母将会是什么,我可以检测到a何时发生?

3 个答案:

答案 0 :(得分:1)

应该可以在body上使用MutationObserver

答案 1 :(得分:1)

DOMNodeInserted或DOMSubtreeModified可能就是你要找的东西。 有关可用的突变事件的完整列表(尽管是ie + +),您可以查看mozilla文档:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

根据你的最终目标,你可以尝试这样的事情,在这个例子中,我假设有一个允许被检测到的独特类。

private=>{allowedAuth=>'Digest',locked=>'FALSE',}profile=>'Default',id=>'123456',indicator=>'FALSE',privacy=>'FALSE',public=>[{configured=>{profileId=>'hello world',}maxSessions=>'3',allowed=>'FALSE',isDefault=>'TRUE',},{allowed=>'FALSE',maxSessions=>'3',implicit=>'1',privateId=>'foo@bar.com',isDefault=>'FALSE',},],

答案 2 :(得分:0)

正如myf所建议的,最好的办法是使用MutationObserver API来观察body元素。在配置观察者时需要将subtree选项设置为true,以便监听body的所有后代的DOM更改,这一点不容易猜到。



// Select the link node
var link = document.querySelector('#link');
// This variable will hold the parent element when the link is appended to it
var detectedParent;

// Insert function triggered by the button for test purposes
var container = document.querySelector('#container2');
function insert() {
    container.appendChild(link);
}    
 
// Create an observer instance
var observer = new MutationObserver(function(mutations) {
  // Traverse every mutation
  mutations.forEach(function(mutation) {
    for (var i = 0; i < mutation.addedNodes.length; i++)
        // Test if the link element has been added to mutation.target
        if (mutation.addedNodes[i] == link) {
            // Store the parent and proudly alert its ID
            detectedParent = mutation.target; 
            alert('ID of link container is : ' + detectedParent.id);
            // Turn off potentially costly DOM listening
            observer.disconnect(); 
        }   
  });    
});
 
// Configure the observer:
var config = { attributes: true, childList: true, characterData: true, 
      // This option allows you to listen to all descendants of body
      subtree: true
};

window.onload = function() {
    observer.observe(document.querySelector('body'), config);
}
&#13;
.container {
    border: 1px solid red;
    height: 50px;
}
&#13;
<div class="container" id="container1"></div>
<div class="container" id="container2"></div>
<div class="container" id="container3"></div>
<div><button onclick="insert()">Insert the link</button></div>
<div class="park"><a id="link">Link</a></div>
&#13;
&#13;
&#13;