跨度文本更改的MutationObserver不会触发 [英] MutationObserver on span text change does not trigger

查看:65
本文介绍了跨度文本更改的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.

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

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

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

推荐答案

添加 childList:true 解决问题。

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


childList:如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为true。

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

在您的示例中,您正在更改 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不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆