javascript - 使用 MutationObserver 检测输入值变化

标签 javascript html mutation-observers

我想检测输入字段中的文本/值何时发生变化。即使我用 js 更改了值,我也想检测到该更改。

这是我目前在 demo in fiddle 中尝试过的内容.

HTML:

<input type="text" id="exNumber"/>

JavaScript:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    // console.log('Mutation type: ' + mutation.type);
    if ( mutation.type == 'childList' ) {
      if (mutation.addedNodes.length >= 1) {
        if (mutation.addedNodes[0].nodeName != '#text') {
           // console.log('Added ' + mutation.addedNodes[0].tagName + ' tag.');
        }
      }
      else if (mutation.removedNodes.length >= 1) {
         // console.log('Removed ' + mutation.removedNodes[0].tagName + ' tag.')
      }
    }
     if (mutation.type == 'attributes') {
      console.log('Modified ' + mutation.attributeName + ' attribute.')
    }
  });   
});

var observerConfig = {
        attributes: true,
        childList: false,
        characterData: false
};

// Listen to all changes to body and child nodes
var targetNode = document.getElementById("exNumber");
observer.observe(targetNode, observerConfig);

最佳答案

要了解发生了什么,必须弄清楚 attribute(内容属性)和 property(IDL 属性)之间的区别。我不会对此进行扩展,因为已经有涵盖该主题的优秀答案:

当您通过键入或通过 JS 更改 input 元素的内容时:

targetNode.value="foo";

浏览器更新 value property 而不是 value attribute(它反射(reflect)了 defaultValue 属性)。

然后,如果我们查看 spec of MutationObserver ,我们将看到 attributes 是可以使用的对象成员之一。因此,如果您显式设置 value 属性:

targetNode.setAttribute("value", "foo");

MutationObserver 将通知属性修改。但是规范列表中没有属性:value 属性无法观察

如果您想检测用户何时更改您输入元素的内容,input event是最直接的方法。如果您需要捕获 JS 修改,请转到 setInterval并将新值与旧值进行比较。

检查这个SO question了解不同的替代方案及其局限性。

关于javascript - 使用 MutationObserver 检测输入值变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383349/

相关文章:

html - 什么是基于 Windows 的免费 HTML/CSS 页面设计应用程序?

android - 如何处理 Android TextView 中的 <embed> 标签

javascript - 删除元素后的 MutationObserver 行为

reactjs - MutationObserver 正在读取旧的 React State

PerformanceObserver 在 Firefox 中抛出错误,在 Chrome 中工作

javascript - 通过类名获取输入字段的值,其中类名是可变的

javascript - 传单矩形立即消失

html - 使用数据库存储和获取网站的 html 页面

javascript - 如果没有 $timeout,UI 路由加载微调器将无法工作

javascript - 如何在动态内容插入后重新定位 Bootstrap Popover?