我正在使用 MutationObserver
等待页面上元素的创建,然后在其上添加一个按钮(使用 init
函数)。
我只需要添加一个按钮,但在此之后不断发生变化。
添加此按钮后,我想 disconnect()
观察者。
我试过这样的:
function detect_node_for_buttons(mutations){
var selector = 'div[class="_2o3t fixed_elem"]';
mutations.forEach(function (mutation){
var element = $(document).find(selector);
if (element){
init();
observer.disconnect();
return;
}
if (!mutation.addedNodes) return;
for (var i = 0; i < mutation.addedNodes.length; i++){
if (mutation.addedNodes[i].matches(selector)){
init();
observer.disconnect();
}
}
});
}
var observer = new MutationObserver(function (mutations){
detect_node_for_buttons(mutations);
});
但它不起作用(可能是因为当我在 detect_node_for_buttons()
中调用 observer.disconnect()
时 observer
尚未定义>)?
我该怎么做?
最佳答案
MutationObserver
中的回调函数使用两个参数调用:突变数组和观察者对象本身。由于您编写代码的方式,detect_node_for_buttons
永远不会获得观察者对象。这将达到目的:
var observer = new MutationObserver(detect_node_for_buttons);
您还必须将此参数添加到函数声明中:
function detect_node_for_buttons(mutations, observer){ ... }
关于javascript - 如何从其回调函数内部断开 MutationObserver 的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354710/