我想要一個特定的函數被調用,每當另一個腳本將div
添加到body
。我如何用MutationObserver觀察整個身體?
我嘗試:
var dom_observer = new MutationObserver(function(mutation) {
console.log('function called');
});
var container = document.body;
console.log(container);
var config = { attributes: true, childList: true, characterData: true };
dom_observer.observe(container, config);
我嘗試設置到container
document.body
(上面的例子),並document.querySelector('body')
。在這兩種情況下,console.log()
顯示null
,我得到以下錯誤:TypeError: Argument 1 of MutationObserver.observe is not an object.
。將div
添加到body
時,不會調用回調函數。
我試着將它設置爲document.getElementsByTagName("body")[0]
和document.documentElement.childNodes[1]
。在這兩種情況下,console.log()
顯示undefined
並且回調函數仍然未被調用。
當你調用這個腳本?您的DOM是否在當時被加載?如果'console.log(document.body)'輸出'null',那麼要麼你不在HTML文檔中,要麼標記的解析只在'
'處。 Ps:如果你不熟悉DOM解析和不同的負載事件,那麼延遲一點你對Mutation Observer的學習,機會很大,你甚至不需要它。 – Kaiido謝謝,那是解決方案。我不得不把代碼放在'jQuery(document).ready(function {...});'中。修復了一切。你可以發佈這個問題的答案。 –