javascript js中的颜色更改不起作用

ou6hu8tu  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(274)

我想改变按钮的颜色,因为它是点击。但目前的代码不工作。它正在应用,但当我点击另一个按钮什么也没有发生。有更好的方法来做到这一点?

const choices = Array.from(document.getElementsByClassName("choice-text"));
choices.forEach((choice) => {
  choice.addEventListener("click", (e) => {
    if (!acceptingAnswers) return;

    // Remove the 'selected' class from all of the choices
    choices.forEach((choice) => {
      choice.parentElement.classList.remove("selected");
    });

    // Add the 'selected' class to the clicked choice
    const selectedChoice = e.target.parentElement;
    selectedChoice.classList.add("selected");

  });
});
.selected {
  background-color: #f1f1f1;
}
<h2 id="question">What is the answer to this questions?</h2>
      <div class="choice-container">
        <p class="choice-prefix">A</p>
        <p class="choice-text" data-number="1">Choice 1</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">B</p>
        <p class="choice-text" data-number="2">Choice 2</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">C</p>
        <p class="choice-text" data-number="3">Choice 3</p>
      </div>
      <div class="choice-container">
        <p class="choice-prefix">D</p>
        <p class="choice-text" data-number="4">Choice 4</p>
      </div>
    </div>
    <div class="btnNav">
      <button class="btn" onclick="navBack(event)">Back</button>
      <button class="btn" onclick="navForward(event)">Next</button>
    </div>
  </div>
</div>
<script src="game.js"></script>
ubof19bj

ubof19bj1#

此代码有效:

choices.forEach((choice) => {
  choice.addEventListener("click", (e) => {
    // Remove the 'selected' class from all of the choices
    choices.forEach((choice) => {
      choice.parentElement.classList.remove("selected");
    });

    // Add the 'selected' class to the clicked choice
    const selectedChoice = e.target;
    selectedChoice.parentElement.classList.add("selected");

    const selectedAnswer = selectedChoice.dataset["number"];
    currentQuestion.userAns = selectedAnswer;
  });
});

但当我回答下一个问题时,它仍然存在。

相关问题