我如何使用“querySelectorAll”?
2022-01-02
93
我的 html:
<label for="answer_1" class="answer_label"><input type="radio" id="answer_1">Answer</label>
<label for="answer_2" class="answer_label"><input type="radio" id="answer_2">Answer</label>
<label for="answer_3" class="answer_label"><input type="radio" id="answer_3">Answer</label>
我的 JS:
var answers = ["Answer_1","Answer_2","Answer_3"];
var answer_labels = document.querySelectorAll(".answer_label");
for (var i = 0; i < answers.length; i++){
answer_labels[i].innerText = answers[i]
}
当我想将文本设置为标签时,出现错误:
Uncaught TypeError: Cannot set properties of undefined (setting 'innerText')
3个回答
for 循环中存在语法错误。
将
for (var i = 0; i < .length; i++)
更改为
for (var i = 0; i < answer_labels.length; i++)
var answers = ["Answer_1","Answer_2","Answer_3"]
var answer_labels = document.querySelectorAll(".answer_label");
for (var i = 0; i < answer_labels.length; i++){
answer_labels[i].innerText = answers[i];
}
<label for="answer_1" class="answer_label"><input type="radio" name="choice" id="answer_1">Answer</label>
<label for="answer_2" class="answer_label"><input type="radio" name="choice" id="answer_2">Answer</label>
<label for="answer_3" class="answer_label"><input type="radio" name="choice" id="answer_3">Answer</label>
Ran Turner
2022-01-02
如果您只想替换标签而不破坏里面的单选按钮输入,您可能应该做这样的事情:
var answers = ["Answer_1","Answer_2","Answer_3"]
document.querySelectorAll(".answer_label").forEach((l,i)=>{
l.innerHTML=l.querySelector("input").outerHTML+answers[i];
})
<label for="answer_1" class="answer_label"><input type="radio" name="choice" id="answer_1">Answer</label>
<label for="answer_2" class="answer_label"><input type="radio" name="choice" id="answer_2">Answer</label>
<label for="answer_3" class="answer_label"><input type="radio" name="choice" id="answer_3">Answer</label>
Carsten Massmann
2022-01-02
问题是我没有在 html 文件中指定“
<!DOCTYPE html>”
...
nyar
2022-01-02