当新节点插入 dom 时,是否会触发 jquery 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3900151/
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
Is there a jquery event that fires when a new node is inserted into the dom?
提问by 3urdoch
Is there an event jquery fires on a dom element when it is inserted into the dom?
将 dom 元素插入 dom 时,是否会在 dom 元素上触发事件 jquery?
E.g. lets say I load some content via ajax and add it to the DOM and in some other piece of javascript I could add an event using .live() so that when an event matching a specific selector is added to the DOM the event fires on said element. Similar to $(document).ready() but on content that is added to the DOM dynamically.
例如,假设我通过 ajax 加载一些内容并将其添加到 DOM 中,在其他一些 javascript 中,我可以使用 .live() 添加一个事件,这样当与特定选择器匹配的事件添加到 DOM 时,事件就会触发说元素。与 $(document).ready() 类似,但内容是动态添加到 DOM 的。
What I am dreaming of:
我的梦想:
$('.myClass').live('ready', function() {
alert('.myClass added to dom');
});
If jquery doesn't support such a thing then is there another way I could achieve this functionality without modifying the code that actually does the initial dom manipulation?
如果 jquery 不支持这样的事情,那么有没有另一种方法可以在不修改实际执行初始 dom 操作的代码的情况下实现此功能?
采纳答案by Nick Craver
The .livequery()
pluginstill serves this niche need, like this:
该.livequery()
插件仍然满足这一利基需求,如下所示:
$('.myClass').livequery(function() {
alert('.myClass added to dom');
});
If you pass it justa callback function like above, it'll run for each new element it finds, both initially and as they're added. Inside the function this
refers to the just-added element.
如果你只是像上面那样传递一个回调函数,它会为它找到的每个新元素运行,无论是最初还是添加时。函数内部是this
指刚刚添加的元素。
.live()
listens for events that bubble, so doesn't fit this "when elements are added" situation, in that respect, .livequery()
(the plugin) wasn't completelyreplaced by the addition of .live()
to core, only the event bubbling portion (for the most part) was.
.live()
侦听冒泡的事件,因此不适合这种“添加元素时”的情况,在这方面,.livequery()
(插件)并没有完全被添加.live()
到核心所取代,只有事件冒泡部分(在大多数情况下) ) 曾是。
回答by Ziggy
deprecated: as per @Meglio's comment below, the
DOMNodeInserted
event is deprecated, and will be removed from the web at some unkown time in the future. For the best results, start learning about the MutationObserver API.see @dain's answer below.
已弃用:根据下面@Meglio 的评论,该
DOMNodeInserted
事件已被弃用,并将在未来某个未知时间从网络中删除。为了获得最佳结果,请开始学习MutationObserver API。请参阅下面的@dain 的回答。
If you bind the 'DOMNodeInserted' eventto the document or body directly, it will get executed every time anything is inserted anywhere. If you want the callback to run only when a particular kind of element is added, you would be wise to use delegated events.
如果您将'DOMNodeInserted' 事件直接绑定到文档或正文,则每次在任何地方插入任何内容时都会执行该事件。如果您希望回调仅在添加特定类型的元素时运行,您最好使用委托事件。
Usually, if you are adding a class of elements to the DOM you will be adding them to a common parent. So attach the event handler like this:
通常,如果您将一类元素添加到 DOM,您会将它们添加到一个公共父级。所以像这样附加事件处理程序:
$('body').on('DOMNodeInserted', '#common-parent', function(e) {
if ($(e.target).attr('class') === 'myClass') {
console.log('hit');
}
});
Basically the same answer as Myke's above, but since you are using a delegated event handler rather than a direct event handler, the code in there will be fired less often.
基本上与Myke 的上述答案相同,但是由于您使用的是委托事件处理程序而不是直接事件处理程序,因此那里的代码将不会经常被触发。
NOTE:
笔记:
$('body').on('DOMNodeInserted', '.myClass', function(e) {
console.log(e.target);
});
This seems to work too... but I don't know why.
这似乎也有效......但我不知道为什么。
回答by dain
If you're living on the cutting edge you can use MutationObserver :)
如果你生活在最前沿,你可以使用 MutationObserver :)
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var list = document.querySelector('ol');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
var list_values = [].slice.call(list.children)
.map( function(node) { return node.innerHTML; })
.filter( function(s) {
if (s === '<br>') {
return false;
}
else {
return true;
}
});
console.log(list_values);
}
});
});
observer.observe(list, {
attributes: true,
childList: true,
characterData: true
});
参见:https: //hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
Edit: this answer is quite old, now MutationObserver is supported by all browsers except Opera Mini: http://caniuse.com/#feat=mutationobserver
编辑:这个答案很旧,现在 MutationObserver 被除 Opera Mini 之外的所有浏览器支持:http: //caniuse.com/#feat=mutationobserver
Also, here's the direct link the the API on MDN: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
此外,这里是 MDN 上 API 的直接链接:https: //developer.mozilla.org/en-US/docs/Web/API/MutationObserver
回答by Myke Cameron
There is no jQuery event, but there is a DOM event: DOMNodeInsertedIntoDocument. You can listen for DOM events using jQuery's on method. So:
没有 jQuery 事件,但有一个 DOM 事件:DOMNodeInsertedIntoDocument。您可以使用 jQuery 的 on 方法侦听 DOM 事件。所以:
$('.myClass').on('DOMNodeInsertedIntoDocument', function() {
alert('myClass was inserted into the DOM');
}
This may be preferable to using liveQuery as that plugin is a bit stale (no updates for 2+ years, only promises support for jQuery 1.2.x).
这可能比使用 liveQuery 更可取,因为该插件有点陈旧(2 年多没有更新,只承诺支持 jQuery 1.2.x)。
回答by igneosaur
Take a look at insertionQuery. It's an interesting library that uses CSS to detect new elements. Because it uses CSS there's no performance hit and you get returned the actual elements matching the selector.
看看插入查询。这是一个有趣的库,它使用 CSS 来检测新元素。因为它使用 CSS,所以不会影响性能,并且会返回与选择器匹配的实际元素。