这当然是一种 hack,但为什么不修补用于插入节点的底层 DOM 方法呢?有几种方法可以做到这一点:
A。你知道吗specific元素将被附加到:
var c = document.getElementById('#container');
c.__appendChild = c.appendChild;
c.appendChild = function(){
alert('new item added');
c.__appendChild.apply(c, arguments);
}
小提琴演示A
B。你知道吗type元素将被附加到:
HTMLDivElement.prototype.__appendChild = HTMLDivElement.prototype.appendChild;
HTMLDivElement.prototype.appendChild = function(){
alert('new item added');
HTMLDivElement.prototype.__appendChild(this,arguments);
}
小提琴演示B
(注意解决方案B不支持IE < 8
或任何其他不支持 DOM 原型的浏览器。)
同样的技术可以很容易地用于所有底层 DOM 突变函数,例如insertBefore
, replaceChild
or removeChild
.
That's the general idea, these demos could be adapted for pretty much any other use case -- say you want to cast a wide net and catch all additions regardless of type AND make sure it works across all browsers everything but IE < 8
? (see example C below)
UPDATE
C.递归地遍历 DOM,交换每个元素上的函数以触发回调,然后将相同的补丁应用于要附加的任何子元素。
var DOMwatcher = function(root, callback){
var __appendChild = document.body.appendChild;
var patch = function(node){
if(typeof node.appendChild !== 'undefined' && node.nodeName !== '#text'){
node.appendChild = function(incomingNode){
callback(node, incomingNode);
patch(incomingNode);
walk(incomingNode);
__appendChild.call(node, incomingNode);
};
}
walk(node);
};
var walk = function(node){
var i = node.childNodes.length;
while(i--){
patch(node.childNodes[i]);
}
};
patch(root);
};
DOMwatcher(document.body, function(targetElement, newElement){
alert('append detected');
});
$('#container ul li').first().append('<div><p>hi</p></div>');
$('#container ul li div p').append('<a href="#foo">bar</a>');
小提琴演示C
UPDATE 2
As Tim Down评论说,上述解决方案也不适用于IE < 8
因为appendChild
不是一个Function
并且不支持call
or apply
。我想你总是可以回到笨重但值得信赖的地方setInterval
方法如果typeof document.body.appendChild !== 'function'
.