jQuery 如何检测jQuery中的新元素创建?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3384398/
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 to detect new element creation in jQuery?
提问by serg
Lets say I have the following code that returns number of anchor elements on a page:
假设我有以下代码返回页面上的锚元素数:
function getLinkCount() {
alert("Links:" + $("a").length);
}
If I call in on document ready it would work as expected. But what if now a new link gets inserted into a page dynamically through javascript, how can I get notified to run link counter function again? (I have no control over a script that could create a new link).
如果我调用文档准备就绪,它将按预期工作。但是,如果现在通过 javascript 动态地将新链接插入到页面中,我如何获得通知以再次运行链接计数器功能?(我无法控制可以创建新链接的脚本)。
Basically I am looking for something similar to live()
only that would be watching element creation event, something like:
基本上,我正在寻找类似于live()
观看元素创建事件的东西,例如:
$("a").live("create", getLinkCount);
that would trigger when a new element is created.
这将在创建新元素时触发。
采纳答案by Nick Craver
You can use the .livequery()
pluginfor this, it runs for each element, including new ones, like this:
您可以为此使用.livequery()
插件,它为每个元素运行,包括新元素,如下所示:
$("a").livequery(getLinkCount);
However, this plugin is out-of-date and is not recommended for current versions of jQuery.
但是,此插件已过时,不推荐用于当前版本的 jQuery。
It's usually easier to do this when you create the elements though, for example if you're doing it after AJAX requests, the .ajaxComplete()
handlermay be a good place, for example:
但是,在创建元素时通常更容易执行此操作,例如,如果您在 AJAX 请求之后执行此操作,则.ajaxComplete()
处理程序可能是一个好地方,例如:
$(document).ajaxComplete(getLinkCount);
This would run after each request, and since you normally create elements in your success
handler, they would already be present when this complete handler runs.
这将在每个请求之后运行,并且由于您通常在success
处理程序中创建元素,因此在此完整处理程序运行时它们已经存在。
回答by mattsh
You could use the DOMSubtreeModified event. For example:
您可以使用 DOMSubtreeModified 事件。例如:
$(document).bind('DOMSubtreeModified',function(){
console.log("now there are " + $('a').length + " links on this page.");
})
回答by Uzair Farooq
You can use the arrive.jslibrary that I developed for the exact same purpose (it uses MutationObserverinternally). Usage:
您可以使用我为完全相同的目的开发的reach.js库(它在内部使用MutationObserver)。用法:
document.arrive('a', function(){
// 'this' refers to the newly created element
var newElem = this;
});
回答by Elliot B.
The accepted answer is from 2010 and uses a jQuery plugin that is no longer being actively maintained. The highest upvoted answer suggests using DOMSubTreeModified
which is now deprecatedand should no longer be used.
接受的答案是从 2010 年开始的,它使用了一个不再积极维护的 jQuery 插件。最高投票的答案建议使用DOMSubTreeModified
which现在已弃用,不应再使用。
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 MutationObserver
to 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 observer
event handler will trigger whenever any node is added or removed from the document
. Inside the handler, we then perform a contains
check to determine if myElement
is now in the document
.
的observer
事件处理程序将触发每当任何节点被添加或从去除document
。在处理程序内部,我们然后执行contains
检查以确定myElement
现在是否在document
.
You don't need to iterate over each MutationRecord stored in mutations
because you can perform the document.contains
check directly upon myElement
.
您不需要遍历存储在的每个 MutationRecord,mutations
因为您可以document.contains
直接对myElement
.
To improve performance, replace document
with the specific element that will contain myElement
in the DOM.
要提高性能,请替换为 DOMdocument
中将包含的特定元素myElement
。