jQuery 确定 HTML 元素是否已动态添加到 DOM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16618876/
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
Determining if a HTML element has been added to the DOM dynamically
提问by Stephen
Is there a way in Javascript or jQuery to find out when a HTML element has been added to the DOM dynamically, either through jQuery.append()
or one of the native Javascript's node manipulators? There are probably several different ways to add HTML elements to the page dynamically, so I'm not sure what event or events I should be listening on.
在 Javascript 或 jQuery 中是否有一种方法可以通过jQuery.append()
本机 Javascript 的节点操作器或其中一个节点操作器动态地将 HTML 元素添加到 DOM 中?可能有几种不同的方法可以动态地向页面添加 HTML 元素,所以我不确定我应该监听什么或哪些事件。
The specific example is that that an anchor tag is being added to the page by a third-party Javascript code (that I cannot modify or easily gleam). I want to change the link's text.
具体的例子是,一个锚标记被第三方 Javascript 代码添加到页面中(我无法修改或轻易闪烁)。我想更改链接的文本。
I am hoping there is something better than a setTimeout()
loop on $(SOME ELEMENT).length > 0
.
(part of which I saw in How can I determine if a dynamically-created DOM element has been added to the DOM?but it's from 2008)
我希望有比setTimeout()
循环更好的东西$(SOME ELEMENT).length > 0
。(我在如何确定动态创建的 DOM 元素是否已添加到 DOM 中看到了其中的一部分?但它是从 2008 年开始的)
采纳答案by ThiefMaster
You can use Mutation Observersfor this purpose - at least if you do not need to support IE/Opera.
您可以为此目的使用Mutation Observers- 至少在您不需要支持 IE/Opera 的情况下。
Here's a short example (taken from html5rocks.com) on how they are used:
这是一个关于如何使用它们的简短示例(取自html5rocks.com):
var insertedNodes = [];
var observer = new WebKitMutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for(var i = 0; i < mutation.addedNodes.length; i++)
insertedNodes.push(mutation.addedNodes[i]);
})
});
observer.observe(document, {
childList: true
});
console.log(insertedNodes);
Note the Webkit
prefix. You need to use the browser-specific prefix. In Firefox it would be Moz
instead.
注意Webkit
前缀。您需要使用特定于浏览器的前缀。在 Firefox 中,它会Moz
改为。
回答by naugtur
Based on the technique by Daniel BuchnerI have created a small library to catch DOM insertions. It's more comfortable to use than the hack itself.
基于Daniel Buchner的技术,我创建了一个小型库来捕获 DOM 插入。使用起来比 hack 本身更舒服。
It uses css animation events, so it's not based on DOMMutationEvents, and it's not Mutation Observer. So it's not slowing down the page and it has a wider support than MutationObserver.
它使用 css 动画事件,所以它不是基于 DOMMutationEvents,也不是 Mutation Observer。所以它不会减慢页面速度,而且它比 MutationObserver 有更广泛的支持。
It has an added benefit of being able to use any CSS selectorsyou want.
它还有一个额外的好处是能够使用任何你想要的CSS 选择器。
Example usage:
用法示例:
insertionQ('.content div').every(function(element){
//callback on every new div element inside .content
});
If you invoke it after DOMReady, it's going to catch only new elements.
如果在 DOMReady 之后调用它,它将只捕获新元素。
See https://github.com/naugtur/insertionQueryfor more options
回答by jpganz18
Why don't you try this? I dont remember the exact function I used but it's kinda similar than this...
你为什么不试试这个?我不记得我使用的确切功能,但它与这个有点相似......
$(document).bind('DOMNodeInserted', function(event) {
alert('inserted ' + event.target.nodeName + // new node
' in ' + event.relatedNode.nodeName); // parent
});
Also, I found some other options at this link:
此外,我在此链接中找到了一些其他选项:
回答by ScumbagNiad
Not sure if anyone is still looking for this but I was and this is the solution I ended up using.
不确定是否有人仍在寻找这个,但我是,这是我最终使用的解决方案。
var __css = document.createElement("style");
__css.type = "text/css";
__css.innerHTML = '.alertInsertion {animation: __nodeInserted 0.001s !important; -o-animation: __nodeInserted 0.001s !important; -ms-animation: __nodeInserted 0.001s !important; -moz-animation: __nodeInserted 0.001s !important; -webkit-animation: __nodeInserted 0.001s !important;}'+
'@keyframes __nodeInserted {from{outline-color: #111;}to{outline-color: #000;}}'+
'@-moz-keyframes __nodeInserted {from{outline-color: #111;}to{outline-color: #000;}}'+
'@-webkit-keyframes __nodeInserted {from{outline-color: #111;}to{outline-color: #000;}}'+
'@-ms-keyframes __nodeInserted {from{outline-color: #111;}to{outline-color: #000;}}'+
'@-o-keyframes __nodeInserted {from{outline-color: #111;}to{outline-color: #000;}}';
document.body.appendChild(__css);
insertion_event = function(event){
if (event.animationName == '__nodeInserted') {
event.target.className = event.target.className.replace(/\balertInsertion\b/,'');
document.dispatchEvent(new CustomEvent('elementInserted', {'target': event.target}));
}
}
document.addEventListener('animationstart', insertion_event, false);
document.addEventListener('MSAnimationStart', insertion_event, false);
document.addEventListener('webkitAnimationStart', insertion_event, false);
Adding the class 'alertInsertion' to the css of the page with a call to the __nodeInserted animation.
通过调用 __nodeInserted 动画将类“alertInsertion”添加到页面的 css。
if the animation is triggered it removes the class from the element and sends out a custom event called elementInserted that includes the element that triggered it.
如果动画被触发,它会从元素中删除类并发出一个名为 elementInserted 的自定义事件,其中包含触发它的元素。
simply use it by adding an event listener:
只需通过添加事件侦听器来使用它:
document.addEventListener('elementInserted', function(e)
{
//Do whatever you want with e.target here.
});
and adding the .alertInsertion class to any elements you want to trigger it.
并将 .alertInsertion 类添加到要触发它的任何元素。
If the element got another class with an animation it will run after this class has been removed.
如果元素有另一个带有动画的类,它将在删除此类后运行。