如何在jquery中检测何时将新元素添加到文档中?

Pra*_*man 13 html javascript css jquery

如何在jquery中检测何时将新元素添加到文档中?

说明:我想知道何时将具有类"column-header"的元素添加到文档中.因为我打算在这些元素上运行一些javascript.

我怎样才能做到这一点 ?我使用jQuery javascript库.

jAn*_*ndy 21

$(document).bind('DOMNodeInserted', function(e) {
    console.log(e.target, ' was inserted');
});
Run Code Online (Sandbox Code Playgroud)

DOMNodeInserted是一个DOM级别3事件.这反过来意味着,您需要一个相当新的浏览器来支持这种事件.

参考:MDC

  • 这是IMO未来发展的最佳选择.但应该注意,IE8及更低版本不支持此功能.我在下面添加了一个答案,如果有人想要快速而肮脏的方式在IE8和更低版本中制作类似这样的工作,并且由于某种原因不想使用livequery. (2认同)
  • 截至2016年[不明事件](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events)已弃用.建议不要在旧项目或新项目中使用这种技术.皮蒂. (2认同)

Ell*_* B. 12

接受的答案使用2011年的过时插件,最高的upvoted答案使用现已弃用的 Mutation事件.

今天,您应该使用MutationObserver来检测何时将元素添加到DOM.现在,MutationObservers在所有现代浏览器(Chrome 26 +,Firefox 14 +,IE11,Edge,Opera 15+等)中得到广泛支持.

这是一个简单的示例,说明如何MutationObserver在将元素添加到DOM时使用a 来监听.

为简洁起见,我使用jQuery语法构建节点并将其插入DOM.

var myElement = $("<div>hello world</div>")[0];

var observer = new MutationObserver(function(mutations) {
   if (document.contains(myElement)) {
        console.log("It's in the DOM!");
        observer.disconnect();
    }
});

observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});

$("body").append(myElement); // console.log: It's in the DOM!
Run Code Online (Sandbox Code Playgroud)

observer每当添加或删除任何节点时,事件处理程序都将触发document.在处理程序内部,我们然后执行contains检查以确定myElement现在是否在document.

您不需要遍历存储的每个MutationRecord,mutations因为您可以document.contains直接执行检查myElement.

要提高性能,请document使用myElementDOM中包含的特定元素替换.


Mar*_*nix 5

如果你想在它上面做一些jQuery,你也可以做一些像livequery(额外的插件):

$('column-header').livequery(function()
{
    // do things here with your column-header, like binding new events and stuff.
    // this function is called when an object is added.
    // check the API for the deletion function and so on.
});
Run Code Online (Sandbox Code Playgroud)

更新:似乎链接被破坏了.试试这个链接