我不明白。 这段代码不应该有用吗?
此处为HTML代码
<div id="past">
<div data-rollid="283585" class="ball ball-1">7</div>
<div data-rollid="283586" class="ball ball-1">4</div>
<div data-rollid="283587" class="ball ball-8">11</div>
<div data-rollid="283588" class="ball ball-8">14</div>
<div data-rollid="283589" class="ball ball-1">2</div>
<div data-rollid="283590" class="ball ball-1">5</div>
<div data-rollid="283591" class="ball ball-1">2</div>
<div data-rollid="283592" class="ball ball-1">6</div>
div data-rollid="283593" class="ball ball-8">13</div>
<div data-rollid="283594" class="ball ball-1">3</div>
</div>
这里是jQuery-Code
$('#past').one('DOMSubtreeModified', function() {
var stuff = $('#panel8-14 .mytotal').html();
var test = '-';
if( test.indexOf(stuff) >= 0){
console.log('asdf');
}
else{
console.log('nope');
}
});
问题是:
当我使用此代码并使用.one()函数时,它只在第一次加载时调用该函数,而不是在div内容发生更改时...
当我使用.bind或.on时,我将它给了2次...
答案 0 :(得分:3)
您可以使用MutationObserver
var target = $("#past").get(0);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.removedNodes.length) {
console.log("removed nodes", mutation.removedNodes[0].nodeValue);
alert("removed nodes");
}
if (mutation.addedNodes.length) {
alert("added nodes");
console.log("added nodes", mutation.addedNodes[0].nodeValue);
}
});
});
var config = {
childList: true,
subtree: true,
characterData: true
};
observer.observe(target, config);
$("#past div:first").text(1); // do stuff
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="past">
<div data-rollid="283585" class="ball ball-1">7</div>
<div data-rollid="283586" class="ball ball-1">4</div>
<div data-rollid="283587" class="ball ball-8">11</div>
<div data-rollid="283588" class="ball ball-8">14</div>
<div data-rollid="283589" class="ball ball-1">2</div>
<div data-rollid="283590" class="ball ball-1">5</div>
<div data-rollid="283591" class="ball ball-1">2</div>
<div data-rollid="283592" class="ball ball-1">6</div>
<div data-rollid="283593" class="ball ball-8">13</div>
<div data-rollid="283594" class="ball ball-1">3</div>
</div>
&#13;