添加到 DOM 时触发 Javascript 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14074161/
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
Trigger Javascript Event on Add to DOM
提问by sgcharlie
Does anyone know how to trigger an event in javascript for an element after it has been added to the DOM?
有谁知道如何在将元素添加到 DOM 后在 javascript 中为该元素触发事件?
The general idea is something like this:
一般的想法是这样的:
var elem = document.createElement('div');
elem.addEventListener('ON_ADD_TO_BODY', function(){console.log(elem.parentNode)});
//... LATER ON ...
parentElemInBody.appendChild(elem); // <- Event is triggered here after append
There are some functions that shouldn't be triggered until you add the element to the DOM so it would make sense to delay execution until the element is added.
有一些函数在您将元素添加到 DOM 之前不应被触发,因此延迟执行直到添加元素是有意义的。
Is there a way to do this without explicitly needing to call them later on or should I be doing some hack that includes a setTimeout
and a check to see if the element has been added to the DOM yet?
有没有办法做到这一点,而无需稍后明确调用它们,或者我应该做一些 hack ,包括 asetTimeout
和 检查元素是否已添加到 DOM 中?
回答by techfoobar
Use the DOMNodeInsertedmutation event.
使用DOMNodeInserted突变事件。
Docs here: https://developer.mozilla.org/en-US/docs/DOM/Mutation_events
文档在这里:https: //developer.mozilla.org/en-US/docs/DOM/Mutation_events
Example usage as given in the above page:
上面页面中给出的示例用法:
element.addEventListener("DOMNodeInserted", function (ev) {
// ...
}, false);
Note: 17th April, 2016
注:2016 年 4 月 17 日
Mutation Events are deprecated as of now. The recommended approach now is Mutation Observers.
突变事件现在已被弃用。现在推荐的方法是 Mutation Observers。