appendChild

时间:2015-05-06 08:01:44

标签: javascript dom

将元素添加到网页后是否会发生事件?

理想情况下我想这样做:

var div = createSomeDiv();
$(div).on("???", function() {
    console.log("Div was added")
});
document.body.appendChild(div); //<---event would fire now

1 个答案:

答案 0 :(得分:6)

请注意,不推荐使用变异事件,在现代浏览器中,您可以使用变异观察器执行此操作:

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