我想检测输入字段中的文本/值何时发生变化。即使我用 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 属性)之间的区别。我不会对此进行扩展,因为已经有涵盖该主题的优秀答案:
- Properties and Attributes in HTML
- .prop() vs .attr()
- What is happening behind .setAttribute vs .attribute=?
当您通过键入或通过 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/