【发布时间】:2017-03-04 21:05:29
【问题描述】:
我对为什么 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 小提琴:
https://jsfiddle.net/0vp8t8x7/
请注意,只有将 textContent 更改为 innerHTML 时,您才会收到警报。
【问题讨论】:
标签: javascript jquery html mutation-observers