The DOMNodeInserted活动已被弃用 https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events所有突变事件都已被突变观察者取代。
But, 在突变观察者中 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver只有用于观察节点属性、内容和子节点突变的配置选项。没有关于它在 DOM 树中的位置的突变。
我能想到的一个“解决方案”是观察从 document.body 开始的所有内容,搜索正在添加的目标节点的一个突变,但这是一种非常糟糕的做任何事情的方式。
那么用 Mutation Observers 替换已弃用的 DOMNodeInserted 的预期方法是什么?
编辑:发现可能重复检测具有特定 ID 的元素何时插入 DOM 中的最有效方法是什么 https://stackoverflow.com/questions/24313108/what-is-the-most-efficient-way-of-detecting-when-an-element-with-a-particular-id?rq=1
再说一遍,所以:搜索栏与标签一起使用比与问题一起使用效果更好。解释这一点可以减少重复并节省用户时间 https://meta.stackoverflow.com/questions/336082/the-searchbar-works-better-with-tags-than-questions-explaining-this-could-reduc?noredirect=1#comment403450_336082
下面是一些代码,您可以在其中看到所有可用的突变观察者配置选项都不会响应添加到页面的元素:
var addMe = document.createElement("div");
var config = {
attributes: true,
childList: true,
characterData: true
}
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
});
observer.observe(addMe, config);
function appendAddMe() {
document.body.appendChild(addMe);
}
div {
height: 50px;
width: 50px;
background: #969;
}
<button onclick="appendAddMe()">Append addMe</button>
我真的不认为这是the回答这个问题,但无论如何我想分享它,因为它总比没有好。
这个问题有一些很好的答案:检测具有特定 ID 的元素何时插入 DOM 中的最有效方法是什么 https://stackoverflow.com/questions/24313108/what-is-the-most-efficient-way-of-detecting-when-an-element-with-a-particular-id?rq=1
特别是这个答案:https://stackoverflow.com/a/25107064/4808079 https://stackoverflow.com/a/25107064/4808079
from 斯凯蒂诺72 https://stackoverflow.com/users/64444/schettino72
iframe 元素触发加载/卸载事件。您可以在要观看的元素中插入一个哑iframe...并自己在原始元素中触发“加载”事件。
function watch($ele){
var $iframe = document.createElement('iframe');
$iframe.style.display = 'none';
$ele.appendChild($iframe);
$iframe.addEventListener('load', function(){
var event = new CustomEvent('load');
$ele.dispatchEvent(event);
});
}
我仍然想保持这个问题的开放性,因为这是一个黑客而不是一个真正的答案。 DOMNodeInserted 可能没有被弃用,所以每个人都可以这样做。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)