下面的代码有效,但是我想做的是应用于“工作2”。 我试过了: paras = Array.from(document.querySelectorAll('。working1 .working2')); 但这不起作用。
代码背景: 不断循环所有元素,直到找到一个空元素。一旦找到,它将用变量替换。然后打破循环。
paras = Array.from(document.querySelectorAll('.working1'));
for(const para of paras) {
if(para.innerHTML === '') {
para.innerHTML = partnumber;
}
<p id="machine1" class="working1"></p>
<p id="machine2" class="working1"></p>
<p id="machine3" class="working1"></p>
<p id="machine4" class="working1"></p>
<p id="machine5" class="working2"></p>
<p id="machine6" class="working2"></p>
<p id="machine7" class="working2"></p>
<p id="machine8" class="working2"></p>
答案 0 :(得分:0)
querySelectorAll('.working1 .working2')
将使用class = working2
选择working1
内querySelectorAll('.working1, .working2')
的元素。
请参见 Groups of selectors on one rule 。
paras = Array.from(document.querySelectorAll('.working1,.working2'));
let partnumber = 0
for(const para of paras) {
partnumber++
if(para.innerHTML === '') {
para.innerHTML = partnumber;
}
}
<p id="machine1" class="working1"></p>
<p id="machine2" class="working1"></p>
<p id="machine3" class="working1"></p>
<p id="machine4" class="working1"></p>
<p id="machine5" class="working2"></p>
<p id="machine6" class="working2"></p>
<p id="machine7" class="working2"></p>
<p id="machine8" class="working2"></p>
答案 1 :(得分:0)
使用document.querySelectorAll('p [class ^ =“ working”]')
paras = Array.from(document.querySelectorAll('p[class^="working"]'));
let partnumber = 0
for(const para of paras) {
partnumber++
if(para.innerHTML === '') {
para.innerHTML = partnumber;
}
}
<p id="machine1" class="working1"></p>
<p id="machine2" class="working1"></p>
<p id="machine3" class="working1"></p>
<p id="machine4" class="working1"></p>
<p id="machine5" class="working2"></p>
<p id="machine6" class="working2"></p>
<p id="machine7" class="working2"></p>
<p id="machine8" class="working2"></p>