0
如何實現突變觀察者的計數器,以限制它在斷開之前監視的更改次數?在我包括的小提琴中,想法是一旦var數大於1,觀察者應該斷開連接。但是因爲變量每次調用觀察者處理程序都會重置,所以它不起作用。我怎樣才能實現我想要做的事情?MutationObserver限制
function mutate(mutations, observer) {
\t var count = 0;
\t console.log('\nThe following mutation(s) occurred:');
\t mutations.every(function(mutation) {
\t \t if (mutation.type === 'attributes') {
\t \t \t console.log('Attribute change.');
\t \t }
\t \t else if (mutation.type === 'characterData') {
\t \t \t console.log('Text change.');
\t \t }
\t \t else if (mutation.type === 'childList') {
\t \t \t if (count > 1) {
\t \t \t \t observer.disconnect();
\t \t \t \t console.log('Disconnected.');
\t \t \t \t return false;
\t \t \t }
\t \t \t console.log('Element change.');
\t \t }
\t \t count++;
\t \t console.log('Count: ' + count);
\t });
}
document.addEventListener('DOMContentLoaded', function() {
\t setTimeout(function() {
\t \t document.getElementById('photo').src = 'http://i.imgur.com/Xw6htaT.jpg';
\t \t document.getElementById('photo').alt = 'Dog';
\t }, 2000);
\t setTimeout(function() {
\t \t document.querySelector('div#mainContainer p').innerHTML = 'Some other text.';
\t }, 4000);
\t setTimeout(function() {
\t \t jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>');
\t }, 6000);
\t setTimeout(function() {
\t \t jQuery('div.insertedDiv').remove();
\t }, 8000);
\t var targetOne = document.querySelector('div#mainContainer');
\t var observer = new MutationObserver(mutate);
\t var config = { attributes: true, characterData: true, childList: true, subtree: true };
\t observer.observe(targetOne, config);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainContainer">
<h1>Heading</h1>
<p>Paragraph.</p>
<img src="http://i.stack.imgur.com/k7HT5.jpg" alt="Photo" id="photo" height="100">
</div>
聲明該函數以外的變量並不重置它 – charlietfl
不使用全局變量,我將如何能夠將該變量傳遞給觀察者的回調函數? –