var observer = new MutationObserver(function(mutations) {
console.log("前:" + mutations.length);// 假如前面输入是2
observer.takeRecords();//是该方法,放置的位置不对吗?
console.log("后:" + mutations.length);// 那后面依然是2,为什么没清除成功呢?
})
参考GPT和自己的思路:
根据你提供的代码,observer.takeRecords()方法应该放在MutationObserver回调函数中,该回调函数在监听的DOM元素发生变化时被调用。在代码中,触发了takeRecords()方法后,变动记录应该被清除了,但由于console.log()函数是异步的,因此在触发takeRecords()方法后马上输出mutations.length的值可能不会立即反映清除后的变动记录数量。可以将console.log()函数放在异步回调函数内部,或者使用setTimeout()函数将其放置在异步队列的末尾,以确保输出的值是正确的。