Javascript 带有外部回调函数代码的变异观测器
我正在尝试重写以下代码:Javascript 带有外部回调函数代码的变异观测器,javascript,callback,mutation-observers,Javascript,Callback,Mutation Observers,我正在尝试重写以下代码: var target = document.querySelector('div#cart'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation.type); }); }); var config = { childList: true, attri
var target = document.querySelector('div#cart');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
var config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);
进入以下脚本:
var target = document.querySelector('div#cart'), observer, moCallback, config;
moCallback = function(mutations) {
mutations.forEach( mutation ) {
console.log(mutation.type);
}
};
var array = moCallback;
observer = new MutationObserver( array );
config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);
第二个脚本对我来说更容易阅读,因为它没有嵌入回调函数;然而,我不能让它工作
如何使用外部回调函数而不是内联匿名函数重写突变观察者?以下是一个工作示例:
/*
if you run this script on this page, you will see that it works as expected.
*/
var target = document.getElementById('header'); // This is the area you're watching for changes. If it's not working, increase the scope (go up the selector cascade to parent elements).
var observer = new MutationObserver(mutate);
function mutate(mutations) {
mutations.forEach(function(mutation) { // When the main image changes...
console.log(mutation.type);
});
}
var config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);
setTimeout(function(){
target.className = "some class";
},2000);
以下是一个工作示例:
/*
if you run this script on this page, you will see that it works as expected.
*/
var target = document.getElementById('header'); // This is the area you're watching for changes. If it's not working, increase the scope (go up the selector cascade to parent elements).
var observer = new MutationObserver(mutate);
function mutate(mutations) {
mutations.forEach(function(mutation) { // When the main image changes...
console.log(mutation.type);
});
}
var config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);
setTimeout(function(){
target.className = "some class";
},2000);
您的forEach在第二个脚本中出错,请将其更改为与script1中的匹配。我更新了forEach()循环,但语法仍然出错。可以使用外部回调调用变异观察者吗?如果是,我还没有在线找到一个可以遵循的示例。回调函数不需要内联定义。您的forEach在第二个脚本中出错,请将其更改为与script1中的一个匹配。我更新了forEach()循环,但语法仍然出错。可以使用外部回调调用变异观察者吗?如果是的话,我还没有在网上找到一个我可以学习的例子。回调函数不需要内联定义。这正是我想要的。非常感谢你,尼克!令人惊叹的。没问题这正是我要找的。非常感谢你,尼克!令人惊叹的。没问题