使用香草javascript和MutationObserver检测输入标签中的值变化 [英] detect value change in input tag with vanilla javascript and MutationObserver

查看:145
本文介绍了使用香草javascript和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);

推荐答案

要弄清正在发生的事情,必须弄清属性(内容属性)和属性之间的区别(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:

  • Properties and Attributes in HTML
  • .prop() vs .attr()
  • What is happening behind .setAttribute vs .attribute=?

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

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

targetNode.value="foo";

浏览器会更新value 属性,但不会更新value 属性(而是反映defaultValue属性).

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

然后,如果我们查看MutationObserver的规格,我们会看到属性是可以使用的对象成员之一.因此,如果您明确设置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.

如果您想检测用户何时更改了输入元素的内容,请 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.

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

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