我對編程很陌生,我正在嘗試開發一個 chrome 擴展。我試圖操作的網站有一個 div 元素,在這個 div 中有多個 div,這些 div 的數量取決于第一個 div 的比例,用戶可以拖動比例。我的問題是,我需要宣告每個變數并讓突變觀察者觀察它們的變化。所以如果一個用戶有 8 個 div,每個 div 都應該被宣告為一個變數,并有一個變異觀察者觀察它。下面是我的代碼:
function tester() {
var child = document.querySelector("#__APP > div > div:nth-child(3) > div > div > div.react-grid-layout.layout > div:nth-child(5) > div > div.css-q57e4p > div > div > div.list-container.css-1kq4s3b > div.list-auto-sizer > div > div");
var childnodesofchild = [child.childNodes];
var divs = [];
console.log(childnodesofchild[0]);
childnodesofchild[0].forEach(consoler);
function consoler() {
//this is the problem
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);
}
}
uj5u.com熱心網友回復:
我仍然不能 100% 確定您的問題是什么。但是在這里,我寫了一個簡單的示例,說明如何在回圈中宣告一些 div 并在回圈中弄亂它的屬性。我希望這是有幫助的。
let colors = ['red','green','blue'];
let innerText = ['A','B','C'];
for (let i = 0; i < colors.length; i ) {
let testDiv = document.createElement('div');
testDiv.className = 'test';
testDiv.style = 'width: 100px; height: 50px; line-height: 50px; text-align: center; color: white;';
testDiv.style.backgroundColor = colors[i];
testDiv.innerHTML = innerText[i];
document.body.appendChild(testDiv);
}
document.getElementById('testBtn').onclick = function() {
let testDivs = document.querySelectorAll('.test');
for (let i = 0; i < testDivs.length; i ) {
testDivs[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
}
<button id="testBtn">Change Div Colors</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412492.html
標籤:
上一篇:反應本機變數未定義
