0

我创建了一个 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 函数根本没有运行。

4

1 回答 1

0

好的,我看到输入值不是 DOM 的一部分,或者它们的更新不会反映在 DOM 中,所以这不起作用。

现在有人给了我一个类似问题的链接 你如何让突变观察者检测文本区域的值变化?

于 2015-05-25T19:32:17.593 回答