您应该将事件附加到文档本身,然后检查事件的目标,如果它是您需要的,请执行您想要的操作。例如:
document.addEventListener("click", function(e){
var element = e.target;
if (element.nodeName === "A") {
//I am gonna do something with <a> elements
//Don't forget to return true if it is an anchor and you want the default event to trigger because if not, it will cancel the event.
} else if (element.className.match("myClass")) {
//OK, this element contains the class i am looking for, let's do something with it
} else if (element.id === "myId") {
//I finally found the element with the ID i was looking for
}
});
更新(对于节点插入):
document.addEventListener("DOMNodeInserted", function(e){
// e is a MutationEvent
var element = e.target;
//Behavior here is pretty much the same as above
if (element.nodeName === "A") {
//I am gonna do something with <a> elements
//Don't forget to return true if it is an anchor and you want the default event to trigger because if not, it will cancel the event.
} else if (element.className.match("myClass")) {
//OK, this element contains the class i am looking for, let's do something with it
} else if (element.id === "myId") {
//I finally found the element with the ID i was looking for
}
});
另一个更新:
我发现这个链接可能会很有趣。它使用动画来确定对象何时被插入到 DOM 中。我用一点 POC 创建了一个小提琴,它似乎可以满足您的要求。