【发布时间】:2015-11-29 17:51:28
【问题描述】:
我想检测输入字段中的文本/值何时发生变化。即使我用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);
【问题讨论】:
-
如果你不耐烦,现在想要一个可怕的、糟糕的、糟糕的修复,那么我为你做了这个:IDL-Property-Observe。运行此库后,您的上述代码将以牺牲原生原型的最佳实践为代价运行良好。干杯!
标签: javascript html mutation-observers