Luk*_*uke 28 html javascript dom mutation-observers
我想使用一个MutationObserver对象来观察我的一些DOM节点的变化.
文档提供了创建MutationObserver对象并在目标上注册它的示例.
// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
Run Code Online (Sandbox Code Playgroud)
说我有上面的代码,但在它下面,我放置这个代码:
var target2 = document.querySelector('#some-other-id');
var config2 = {attributes: true, subtree: true};
observer.observe(target2, config2);
Run Code Online (Sandbox Code Playgroud)
威尔observer:
target吗?target2吗?scn*_*iro 26
观察者现在将观察两个目标 - target并target2根据您的定义.不会抛出任何错误,并且target不会"取消注册"以支持target2.不会出现意外或其他行为.
这是一个MutationObserver在两个有限元素上使用相同的样本.要查看此内容,请<span>从每个contenteditable元素中删除节点,并查看两个观察元素的行为跨度.
<div id="myTextArea" contenteditable="true">
<span contenteditable="false">Span A</span>
</div>
<div id="myTextArea2" contenteditable="true">
<span contenteditable="false">Span B</span>
</div>
Run Code Online (Sandbox Code Playgroud)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//console.log($(mutation.removedNodes)); // <<-- includes text nodes
$(mutation.removedNodes).each(function(value, index) {
if(this.nodeType === 1) {
console.log(this)
}
});
});
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe($('#myTextArea')[0], config);
observer.observe($('#myTextArea2')[0], config);
Run Code Online (Sandbox Code Playgroud)
JSFiddle Link - 演示
请注意,我已为此第一个演示回收了相同的配置,但是,放置一个新配置将是该观察元素所独有的.按照定义的示例config2,如果使用#myTextArea2,您将看不到每个配置选项的已记录节点,但请注意观察者#myTextArea不受影响.
JSFiddle Link - 演示 - 配置独占性