我正在做一个测验。我希望能够按下回答按钮,并让模式背景改变颜色。最初,我使用querySelector作为按钮类(class='ansbtn'(,并且只能与一个按钮交互。然后意识到我使用了queryselectorAll,现在它甚至无法识别点击,甚至一个按钮都无法识别。参见下方的代码
// Get answer options A,B,C,D to change text
let answerA = document.querySelector('#A')
let answerB = document.querySelector('#B')
let answerC = document.querySelector('#C')
let answerD = document.querySelector('#D')
// Get answer button pressed
let ansbtnpress = document.querySelectorAll(".ansbtn")
ansbtnpress.addEventListener("click", checkAnswer);
function checkAnswer() {
if (ansbtnpress.innerHTML == questions[0].correct) {
anscontainer.style.backgroundColor = "green";
console.log(ansbtnpress.innerHTML);
} else {
anscontainer.style.backgroundColor = "red";
}
}
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div class="container">
<div id="question">What is an Epidemic?</div>
<div id="answer-buttons" class="btn-grid">
<button class="ansbtn" id="A">Answer 1</button>
<button class="ansbtn" id="B">Answer 2</button>
<button class="ansbtn" id="C">Answer 3</button>
<button class="ansbtn" id="D">Answer 4</button>
</div>
</div>
</div>
</div>
有什么想法可以解释为什么它无法识别我正在点击任何按钮?
使用querySelectorAll
将获得具有ansbtn
类的所有按钮的列表查询,因此为了在它们上调用addEventListener
,您就像在说:
使该列表可点击
,这没有意义,所以你需要在每个特定按钮上调用addEventListener
,如下所示:
ansbtnpress[0].addEventListener("click", checkAnswer);
function checkAnswer(){
if(ansbtnpress.innerHTML == questions[0].correct){
anscontainer.style.backgroundColor = "green";
console.log(ansbtnpress.innerHTML);
}else {
anscontainer.style.backgroundColor = "red";
}
}
这将使第一个可点击的
如果你想让它们都可以点击,你可以用for loop
:迭代它们
for(let index = 0; index < ansbtnpress.length; index+=1) {
ansbtnpress[index].addEventListener("click", checkAnswer);
function checkAnswer(){
if(ansbtnpress.innerHTML == questions[0].correct){
anscontainer.style.backgroundColor = "green";
console.log(ansbtnpress.innerHTML);
}else {
anscontainer.style.backgroundColor = "red";
}
})}