0
將元素添加到網頁後是否發生了事件?appendChild後發生的事件
理想我想這樣做:
var div = createSomeDiv();
$(div).on("???", function() {
console.log("Div was added")
});
document.body.appendChild(div); //<---event would fire now
將元素添加到網頁後是否發生了事件?appendChild後發生的事件
理想我想這樣做:
var div = createSomeDiv();
$(div).on("???", function() {
console.log("Div was added")
});
document.body.appendChild(div); //<---event would fire now
注意突變事件已被棄用,在現代瀏覽器你會用變異觀察家做到這一點:
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
這是完美謝謝。 – user1529413