javascript – 类的MutationObserver(不是id)
作者:互联网
使MutationObserver适用于#someID并不是问题,但是它能使它适用于.someClass的方法是什么?
目前我正在使用以下内容:
// this example doensn't work,
// as well as many another attempts
var target = document.querySelectorAll(".someClass");
for (var i = 0; i < target.length; i++) {
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var foo = target[i].getAttribute("someAttribute")
if (foo == "someValue")
foo.style.backgroundColor = "red";
});
});
// configuration of the observer
var config = { attributes: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
}
解决方法:
你有几个问题:
> iterator:执行代码后,target [i]不是您所期望的(var foo = target [i] .getAttribute(“someAttribute”)),因为在运行此行时迭代完成,我的值为target.length,所以target [i]不存在
>属性没有样式(foo.style.backgroundColor),需要引用目标元素
>您将整个集合传递给观察者(observer.observe(target,config);)您只需要一个目标元素
这是修复上面列出的错误并将循环代码外部化为函数以便更容易进行目标引用之后的工作代码:
var target = document.querySelectorAll(".c");
for (var i = 0; i < target.length; i++) {
create(target[i]);
}
function create(t) {
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var foo = t.getAttribute("aaa")
if (foo == "vvv")
t.style.backgroundColor = "red";
});
});
// configuration of the observer
var config = {
attributes: true
};
// pass in the target node, as well as the observer options
observer.observe(t, config);
}
// let's change an attribute in a second
setTimeout(function(){
target[2].setAttribute('aaa', 'vvv');
}, 1000);
.c {
width: 50px;
height: 50px;
display: inline-block;
border: 1px solid black
}
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
UPDATE
这是一个包含最少编辑的示例:
> var foo = target [i] .getAttribute(“someAttribute”)更改为var foo = mutation.target.getAttribute(“someAttribute”)而不是传入的目标元素
var target = document.querySelectorAll(".someClass");
for (var i = 0; i < target.length; i++) {
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var foo = mutation.target.getAttribute("someAttribute")
if (foo == "someValue")
mutation.target.style.backgroundColor = "red";
});
});
// configuration of the observer
var config = { attributes: true };
// pass in the target node, as well as the observer options
observer.observe(target[i], config);
}
// let's change an attribute in a second
setTimeout(function(){
target[2].setAttribute('someAttribute', 'someValue');
}, 1000);
.someClass {
width: 50px;
height: 50px;
display: inline-block;
border: 1px solid black
}
<div class="someClass"></div>
<div class="someClass"></div>
<div class="someClass"></div>
<div class="someClass"></div>
标签:javascript,mutation-observers 来源: https://codeday.me/bug/20190519/1135795.html