MutationObserver on span text change does not trigger

吃可爱长大的小学妹 提交于 2019-12-10 16:00:00

问题


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

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

JSFiddle

$(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');" />

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


回答1:


Adding childList: true fixes the problem.

From https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver:

childList: Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.

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');" />


来源:https://stackoverflow.com/questions/33521073/mutationobserver-on-span-text-change-does-not-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!