本文介绍了跨度文本更改的MutationObserver不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个简单的例子而不是实际的事情。

This is just a boiled down example not an actual thing.

Still MutationObserver没有触发,所以我对其工作方式的假设是错误的。

Still MutationObserver isn't firing so my assumption on how it works is wrong.

$(function() {
  var editButtonVisibility = function() {
    console.log('bam');
  }

  $('#RiskPostcodeSummary span').on("change", function() {
    console.log("pew pew");
  });

  var observer = new MutationObserver(function(e) {
    editButtonVisibility();
  });

  observer.observe($('#RiskPostcodeSummary span')[0], {
    characterData: true
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
  <span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />

为什么不是 MutationObserver 在我更改< span> 中的文字时触发?

Why isn't MutationObserver firing when I change text in <span>?

推荐答案

添加 childList:true 解决问题。

来自:

在您的示例中,您正在更改 span 元素。

In your example, you're changing the text node child of the span element.

$(function() {
  var editButtonVisibility = function() {
    console.log('bam');
  }

  $('#RiskPostcodeSummary span').on("change", function() {
    console.log("pew pew");
  });

  var observer = new MutationObserver(function(e) {
    editButtonVisibility();
  });

  observer.observe($('#RiskPostcodeSummary span')[0], {
    characterData: true,
    childList: true
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
  <span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />

这篇关于跨度文本更改的MutationObserver不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 02:55