类的MutationObserver(不是id)

时间:2016-01-30 03:08:20

标签: javascript mutation-observers

使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);
}

1 个答案:

答案 0 :(得分:5)

你遇到了一些问题:

  • 迭代器:target[i]不是您在执行代码时所期望的(var foo = target[i].getAttribute("someAttribute")),因为在运行此行时迭代完成,i的值为{{ 1}},所以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>已更改为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
}