假设我有一个div#parent
元素,我使用jQuery向其中添加和删除元素。那么,我如何检测到这样的事件在div#parent
元素上发生了呢?
假设我有一个div#parent
元素,我使用jQuery向其中添加和删除元素。那么,我如何检测到这样的事件在div#parent
元素上发生了呢?
不要使用DOM节点插入和删除等变异事件。
相反,使用DOM Mutation Observers,它们在除IE10及以下版本外的所有现代浏览器中都得到支持(Can I use)。变异观察器旨在取代变异事件(已被弃用),因为发现其设计存在缺陷,导致性能较低。
var x = new MutationObserver(function (e) {
if (e[0].removedNodes) console.log(1);
});
x.observe(document.getElementById('parent'), { childList: true });
按照@Qantas在他的答案中提到的建议,您可以使用Mutation Observers
以下方法已经被弃用
您可以使用DOMNodeInserted和DOMNodeRemoved
$("#parent").on('DOMNodeInserted', function(e) {
console.log(e.target, ' was inserted');
});
$("#parent").on('DOMNodeRemoved', function(e) {
console.log(e.target, ' was removed');
});
DOMNodeInserted
或 DOMNodeRemoved
,则执行函数 {}
。 - wharfdale我无法在顶部答案下面发表评论,但是为了回答你的问题@DenisKolodin,为了监听自毁,您可以这样做:
function watchElForDeletion(elToWatch, callback, parent = document.querySelector('body')){
const observer = new MutationObserver(function (mutations) {
// loop through all mutations
mutations.forEach(function (mutation) {
// check for changes to the child list
if (mutation.type === 'childList') {
// check if anything was removed and if the specific element we were looking for was removed
if (mutation.removedNodes.length > 0 && mutation.removedNodes[0] === elToWatch) {
callback();
}
}
});
});
// start observing the parent - defaults to document body
observer.observe(parent, { childList: true });
};
默认情况下,父元素为body元素,并且仅在删除您要查找的特定元素时运行回调函数。
DOMSubtreeModified
事件。$("#parent").bind("DOMSubtreeModified",function(){
console.log('changed');
});
我认为我们可以使用socket.io!
因为我们需要检测应该添加哪个元素,然后可能猜测哪个元素将被移除。
也许这是可能的。
谢谢。