在不使用自定义触发器的情况下,如何使用jQuery侦听插入到DOM中的元素

How can I listen for an element being inserted into the DOM with jQuery without using custom triggers?

本文关键字:jQuery 插入 元素 DOM 何使用 自定义 触发器 情况下      更新时间:2023-09-26

我想听听在页面中插入一些html的另一段代码。我不能控制那个代码,所以我不能做.trigger('custom_event')$(document).on('custom_event')

此外,我要监听的插入的div嵌套在插入的html中。

以下是我现在拥有的:

$(document).on('DOMNodeInsertedIntoDocument', "#inserted", function () {
    console.log("Inserted into document:", $(this));
});
$(document).ready(function () {
    var new_node = $('<div><div id="inserted">New Div</div></div>');
    $("body").append(new_node);
});

http://jsfiddle.net/AeHxQ/5/

为什么事件没有被触发?

您可以使用带有少量JavaScript的CSS动画来检测元素何时添加到DOM中。这里对该技术进行了解释:http://davidwalsh.name/detect-node-insertion