javascript 如何检测何时将新元素添加到 jquery 中的文档?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4780822/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect when a new element has been added to the document in jquery?
提问by Prakash Raman
How can I detect when a new element has been added to the document in jquery ?
如何检测何时将新元素添加到 jquery 中的文档?
Explanation: I want to know when an element with class "column-header" has been added to the document. As I plan to run some javascript on those elements.
说明:我想知道何时将具有“column-header”类的元素添加到文档中。因为我计划在这些元素上运行一些 javascript。
How can I do this ? I use jQuery javascript library.
我怎样才能做到这一点 ?我使用 jQuery javascript 库。
采纳答案by Marnix
If you want to do some jQuery on it, you can also do something like livequery (extra plugin):
如果你想在上面做一些 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.
});
UPDATE: It seems that the link was broken. Try this link
更新:链接似乎已损坏。试试这个链接
回答by jAndy
回答by Elliot B.
The accepted answer uses an obsolete plugin from 2011 and the highest upvoted answer uses Mutation events which are now deprecated.
接受的答案使用 2011 年的过时插件,最高投票的答案使用 Mutation 事件,现在已弃用。
Today, a MutationObserveris what you should use to detect when an element has been added to the DOM.MutationObservers are now widely supported across all modern browsers (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc).
今天,你应该使用MutationObserver来检测元素何时被添加到 DOM。MutationObservers 现在在所有现代浏览器(Chrome 26+、Firefox 14+、IE11、Edge、Opera 15+ 等)中得到广泛支持。
Here's a simple example of how you can use a MutationObserverto listen for when an element is added to the DOM. 
这是一个简单的示例,说明如何使用 aMutationObserver来侦听何时将元素添加到 DOM。
For brevity, I'm using jQuery syntax to build the node and insert it into the DOM.
为简洁起见,我使用 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!
The observerevent handler will trigger whenever any node is added or removed from the document. Inside the handler, we then perform a containscheck to determine if myElementis now in the document.
的observer事件处理程序将触发每当任何节点被添加或从去除document。在处理程序内部,我们然后执行contains检查以确定myElement现在是否在document.
You don't need to iterate over each MutationRecord stored in mutationsbecause you can perform the document.containscheck directly upon myElement.
您不需要遍历存储在的每个 MutationRecord,mutations因为您可以document.contains直接对myElement.
To improve performance, replace documentwith the specific element that will contain myElementin the DOM.
要提高性能,请替换为 DOMdocument中将包含的特定元素myElement。
回答by Ivan
I would use setInterval to repeatedly check for element. eg.
我会使用 setInterval 反复检查元素。例如。
var curLength=0;
setInterval(function(){
  if ($('.column-header').length!=curLength){
    curLength=$('.column-header').length;
    // do stuff here
  }
},100);
this code will check for any new .colum-header elements every 100 ms
此代码将每 100 毫秒检查一次任何新的 .colum-header 元素
回答by Ben Lesh
I think the DOMNodeInserted method mentioned above is probably the sexiest choice, but if you need something that is going to work with IE8 and lower, you could do something like the following:
我认为上面提到的 DOMNodeInserted 方法可能是最性感的选择,但是如果您需要一些可以在 IE8 及更低版本上使用的东西,您可以执行以下操作:
// wrap this up in en immediately executed function so we don't 
// junk up our global scope.
(function() {
   // We're going to use this to store what we already know about.
   var prevFound = null;
   setInterval(function() {
      // get all of the nodes you care about.
      var newFound = $('.yourSelector');
      // get all of the nodes that weren't here last check
      var diff = newFound.not(prevFound);
      // do something with the newly added nodes
      diff.addClass('.justGotHere');
      // set the tracking variable to what you've found.
      prevFound = newFound;
   }, 100);
})();
That is just the basic idea, you can change that however you want, make a method out of it, keep the return value of the setInterval so you can stop it, or whatever you need to do. But it should get the job done.
这只是基本思想,您可以随心所欲地更改它,从中创建一个方法,保留 setInterval 的返回值以便您可以停止它,或者您需要做的任何事情。但它应该完成工作。
回答by 72lions
You should check out the jQuery Mutation Events. I believe that it is what you are looking for.
您应该查看jQuery Mutation Events。我相信这就是你要找的。
回答by dtdi
Up to 2013 MutationEvents are deprecated. If anyone else has got problems detecting new elements in the dom, you can use MutationObservers Instead: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
最多 2013 年 MutationEvents 已弃用。如果其他人在检测 dom 中的新元素时遇到问题,您可以改用 MutationObservers:https: //developer.mozilla.org/en-US/docs/Web/API/MutationObserver
回答by Harish
if you want to set same functions for all the elements with class column-headerThen you may use jquery live()
如果你想为所有具有 class 的元素设置相同的函数column-header那么你可以使用 jquery live()
$(".column-header").live("click",function(){});
回答by bogatyrjov
How about using a poll - keep searching for an element with class "column-header", until you find it and then perform action. Seems simple.
使用民意调查如何 - 继续搜索具有“列标题”类的元素,直到找到它然后执行操作。看起来很简单。
回答by Vivek
try this...
试试这个...
if($('.column-header')){  
//do something...
} 
or you can also do something like this..it will be more generic
或者你也可以做这样的事情..它会更通用
jQuery.exists = function(selector) { return ($(selector).length > 0); }
if ($(selector).exists()) {
  // Do something
}

