在appendChild之后发生的事件 [英] Event that occurs after appendChild
本文介绍了在appendChild之后发生的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将元素添加到网页后是否发生事件?
Is there an event that occurs after an element is added to a webpage?
理想情况下,我想这样做:
Ideally I want to do this:
var div = createSomeDiv();
$(div).on("???", function() {
console.log("Div was added")
});
document.body.appendChild(div); //<---event would fire now
推荐答案
请注意,不建议使用突变事件,在现代浏览器中,您可以使用突变观察者进行此操作:
Note that mutation events are deprecated, in modern browsers you'd do this with mutation observers:
var onAppend = function(elem, f) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(m) {
if (m.addedNodes.length) {
f(m.addedNodes)
}
})
})
observer.observe(elem, {childList: true})
}
onAppend(document.body, function(added) {
console.log(added) // [p]
})
var p = document.createElement('p')
p.textContent = 'Hello World'
document.body.appendChild(p) // will trigger onAppend callback
这篇关于在appendChild之后发生的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文