我已经创建了一个JSfiddle示例,说明我如何测试MutationObserver。死得很简单。 http://jsfiddle.net/bqcpna3k/6/
HTML
<div>
<input name='a' value='1'>
<input name='b' value='1'>
<input name='c' value='1'>
<input name='d' value='1'>
<input name='e' value='1'>
<input name='f' value='1'>
</div>
<div>
<p>would like to update the labels from mutationobserver function</p>
a <label id='a'></label>
b <label id='b'></label>
c <label id='c'></label>
d <label id='d'></label>
e <label id='e'></label>
f <label id='f'></label>
</div>
的Javascript
var inputs=[];
//decide which inputs to give interesting changing numbers to
$('input').each(function(i,e){
if (Math.random()>0.5) inputs.push(e); else e.value='ignore';
});
//change the special input boxes numbers regularly
setInterval(function() {
inputs.forEach(function(e){e.value=Math.floor(Math.random()*50);});
},1000);
//this function is supposed to run reliably when the numbers change
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
//var target = $('input').closest('div')[0]; //have never had any success in getting Mutation Events to fire when trying to observe a div
var target = document.body;//simple
//activate the MutationObserver
observer.observe(target, { attributes: true, childList: true, characterData: true });
console.log('finished staring up');
CSS
label {display:block}
在其他测试中,我遇到了使MutationObserver函数可靠运行的问题。我在观察div而不是document.body时遇到了问题。
在上面的小提琴中,MutationObserver函数根本不运行。
答案 0 :(得分:0)
好的我看到输入值不是DOM的一部分,或者它们的更新没有反映在DOM中,所以这不起作用。
现在有人给了我一个类似问题的链接 How do you get a mutation observer to detect a value change of a textarea?