【问题标题】:MutationObserver for class (not for id)类的 MutationObserver(不适用于 id)
【发布时间】:2016-05-07 22:56:00
【问题描述】:

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

【问题讨论】:

    标签: javascript mutation-observers


    【解决方案1】:

    您遇到了一些问题:

    • iterator: target[i] 不是你所期望的,一旦代码被执行(var foo = target[i].getAttribute("someAttribute")),因为在运行这行时迭代已经完成,i 的值是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
    }
    <div class="someClass"></div>
    <div class="someClass"></div>
    <div class="someClass"></div>
    <div class="someClass"></div>

    【讨论】:

    • Shomz,你可以看看我的另一个问题(100 rep bounty),链接到这个?我正在尝试找到一种方法来断开和重新连接观察者与您的代码示例。这是链接:stackoverflow.com/questions/35290789/…
    • 嗨,约翰,你确定是这个问题吗?因为那个人有 2 天前的答案,而且没有赏金。
    • 嗨!链接是正确的,我验证了。大卫的回答可能是对的,但我不明白,我决定问你,以获得更权威的答案。赏金已开放 - here is the screenshot。可能是一些错误 - StackOverflow 今晚工作得很奇怪。试着现在看看,或者可能是明天。如果赏金仍然不可见-那么,请告诉我!我会询问元数据,或者可能会写消息给支持团队。
    • 啊,它现在在那里,我可以发誓当我看的时候它不在那里。无论如何,我不知道您不理解或不喜欢 David 的回答 - 他对 MDN 文档进行了正确的引用,但也许与您的代码更相似的示例会更好。我会再看看,看看今晚或明天我能不能想出更好的东西。
    • 哦,顺便说一句。看看你是否可以取消赏金,因为问题是关于一个糟糕的变量范围,而且你不应该浪费你的代表,直到你得到更多。 :)
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2020-12-20
    相关资源
    最近更新 更多