我绞尽脑汁想知道为什么 MutationObserver 没有检测到使用 textContent 完成的文本更改。
HTML
<div id="mainContainer">
<h1>Heading</h1>
<p>Paragraph.</p>
</div>
JavaScript
function mutate(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.type);
});
}
jQuery(document).ready(function() {
setTimeout(function() {
document.querySelector('div#mainContainer > p').textContent = 'Some other text.';
}, 2000);
var target = document.querySelector('div#mainContainer > p')
var observer = new MutationObserver( mutate );
var config = { characterData: true, attributes: false, childList: false, subtree: true };
observer.observe(target, config);
});
在上面的脚本中,段落元素的文本内容明显发生了变化,但 MutationObserver 没有检测到。
但是,如果您将 textContent 更改为 innerHTML,您将收到“characterData”已更改的警告。
为什么 MutationObserver 检测到 innerHTML 而不是 textContent?
这是 JS fiddle :
https://jsfiddle.net/0vp8t8x7/
请注意,只有将 textContent 更改为 innerHTML 时,您才会收到提醒。
最佳答案
这是因为 textContent
触发了不同的 change而不是 innerHTML
,并且您的观察者配置未配置为观察 textContent
所做的更改。
textContent
更改目标的子文本节点。根据MDN设置textContent
:
Setting this property on a node removes all of its children and replaces them with a single text node with the given value.
虽然 innerHTML
改变了元素本身,它是子树。
因此,要捕获 innerHTML
,您的配置应该是:
var config = { characterData: true, attributes: false, childList: false, subtree: true };
在捕获 textContent
时使用:
var config = { characterData: false, attributes: false, childList: true, subtree: false };
演示:
function mutate(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.type);
});
}
setTimeout(function() {
document.querySelector('div#mainContainer > p').textContent = 'some other text.';
}, 1000);
var target = document.querySelector('div#mainContainer > p')
var observer = new MutationObserver( mutate );
var config = { characterData: false, attributes: false, childList: true, subtree: false };
observer.observe(target, config);
<div id="mainContainer">
<h1>Heading</h1>
<p>Paragraph.</p>
</div>
关于javascript - Mutation Observer 未检测到文本更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195514/