本文介绍了使用 MutationObserver 检测输入值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to detect when text/value change in input field. Even if I change the value with js, I want to detect that changes.

这是我迄今为止在小提琴演示中尝试过的.

Here's what I've tried so far in 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 之间的区别em>(IDL 属性).我不会对此进行扩展,因为在 SO 中已经有很好的答案涵盖了该主题:

To understand what is going on is necessary to clear up the difference between attribute (content attribute) and property (IDL attribute). I won't expand on this as in SO there are already excellent answers covering the topic:

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

When you change the content of a input element, by typing in or by JS:

targetNode.value="foo";

浏览器更新 value property 但不更新 value attribute(它反映了 defaultValue 属性代替).

the browser updates the value property but not the value attribute (which reflects the defaultValue property instead).

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

Then, if we look at the spec of MutationObserver, we will see that attributes is one of the object members that can be used. So if you explicitly set the value attribute:

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

MutationObserver 将通知属性修改.但是规范列表中没有像 properties 这样的东西:value 属性无法观察.

MutationObserver will notify an attribute modification. But there is nothing like properties in the list of the spec: the value property can not be observed.

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

If you want to detect when an user alters the content of your input element, the input event is the most straightforward way. If you need to catch JS modifications, go for setInterval and compare the new value with the old one.

检查这个SO问题 了解不同的替代方案及其局限性.

Check this SO question to know about different alternatives and its limitations.

这篇关于使用 MutationObserver 检测输入值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:32