根据 children 的数量在 javascript 中声明多个变量

declaring multiple variables in javascript based on the quantity of children

我是编程新手,正在尝试开发 chrome 扩展。我试图操纵的网站有一个 div 元素,在这个 div 中有多个 div,这些 div 的数量取决于第一个的规模div 且比例可由用户拖动。我的问题是,我需要声明这些变量中的每一个,并让突变观察者观察它们的变化。因此,一个用户可能在可拖动 window 中有 8 个 div,而另一个用户可能在其中有 12 个 div,所以我想分别有 8 个或 12 个突变观察者。下面是我的代码:

span1 = document.getElementsByClassName("text right")[0];



const observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        var spantext = span1.textContent;
        var spandiv = span1.parentNode;
        
        
        if (mutation.addedNodes) {
            if (spantext > avg) {
                spandiv.style.backgroundColor = "#E8E8E8"
                spandiv.style.color = "black";
                spandiv.style.opacity = "0.7";
            }
            if (spantext < avg) {
                spandiv.style.backgroundColor = "black";
                spandiv.style.color = "white";
                spandiv.style.opacity = "1";
            }
        }
    })
});
const options = {
    childList: true,
    subtree: true,
    attributes: true,
    characterData: true
};
observer.observe(span1, options);
span2 = document.getElementsByClassName("text right")[1];
const observer2 = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        var spantext = span2.textContent;
        var spandiv = span2.parentNode;
        
        if (mutation.addedNodes) {
            if (spantext > avg) {
                spandiv.style.backgroundColor = "#E8E8E8"
                spandiv.style.color = "black";
                spandiv.style.opacity = "0.7";
                
            }
            if (spantext < avg) {
                spandiv.style.backgroundColor = "black";
                spandiv.style.color = "white";
                spandiv.style.opacity = "1";
                
            }
        }
    })
});
observer2.observe(span2, options);

如你所见,我制作了 2 个变异观察器,它们正在观察两个 div,但这仅在用户在其可拖动 [=27] 中有 2 个 div 时才实用=]. 非常感谢您的帮助。

使用循环将突变观察器添加到所有 DIV。

document.querySelector(".text.right").forEach(span => {
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var spantext = span.textContent;
      var spandiv = span.parentNode;

      if (mutation.addedNodes) {
        if (spantext > avg) {
          spandiv.style.backgroundColor = "#E8E8E8"
          spandiv.style.color = "black";
          spandiv.style.opacity = "0.7";
        }
        if (spantext < avg) {
          spandiv.style.backgroundColor = "black";
          spandiv.style.color = "white";
          spandiv.style.opacity = "1";
        }
      }
    })
  });
  const options = {
    childList: true,
    subtree: true,
    attributes: true,
    characterData: true
  };
  observer.observe(span, options);
});