vmo*_*eco 3 javascript mutation-observers
我正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用(也许是因为当我在detect_node_for_buttons() 中调用observer.disconnect()时尚未定义观察者)?
我怎么办?
回调函数 inMutationObserver使用两个参数调用:突变数组和观察者对象本身。由于您编写代码的方式,detect_node_for_buttons永远不会获得观察者对象。这将解决问题:
var observer = new MutationObserver(detect_node_for_buttons);
Run Code Online (Sandbox Code Playgroud)
您还必须将此参数添加到函数声明中:
function detect_node_for_buttons(mutations, observer){ ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1873 次 |
| 最近记录: |