MutationObserver をテストする方法の JSfiddle の例を作成しました。シンプル。 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 関数を確実に実行するのに問題がありました。また、document.body の代わりに div を観察する際にも問題がありました。
上記のフィドルでは、MutationObserver 関数はまったく実行されません。