简体   繁体   English

js中的颜色变化不起作用

[英]The change of the color in js doesn't work

I want color of the button to change as it is clicked.我希望按钮的颜色在单击时发生变化。 But current code doesn't work.但是当前代码不起作用。 It is being applyied but when I click another button nothing happends.它正在被应用但是当我点击另一个按钮时没有任何反应。 Is there better way to do this?有更好的方法吗?

 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>

This code worked:此代码有效:

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;
  });
});

But it stays when I go to the next question.但是当我 go 到下一个问题时它仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM