1
如何讓觀察實例MutationObserver
忽略一些由我的代碼導致的DOM更改? 例如(使用jQuery):MutationObserver:忽略DOM動作
//initialize MutationObserver
var mo = new MutationObserver(mutations => console.log(mutations));
mo.observe(document.body, {attributes: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true, childList: true});
//case 1: perform a removal
$('.someDiv').remove();
//in this case an action is logged by MO
//case 2: perform a removal with a disconnected MO
mo.disconnect();
$('.someDiv').remove();
mo.observe(document.body, {...});
//in this case an action is logged again!
在這兩種情況下,MO記錄我所做的DOM的所有更改。還有就是我想出的唯一辦法:
//case 3: perform a removal with a disconnected MO, turning on after a timeout
mo.disconnect();
$('.someDiv').remove();
setTimeout(() => mo.observe(document.body, {...}), 500); //pseudo
//in this case MO skips an action above
但它不是這個問題的最佳解決方案,因爲可以有超時期間可由用戶造成頁面上一些其他動作,或MutationObserver的回調可能在超時之後的某個時間調用。