开发者问题收集

如何使用 javascript 更改特定单选按钮选项的颜色?

2020-05-08
1029

我正在使用 JavaScript 创建测验应用程序。当用户根据答案单击输入按钮时,我想更改其颜色。如果答案为真,则需要将颜色更改为红色,如果答案错误,则颜色需要更改为红色。每个问题只需选择一个选项。如果用户选择了一个选项,则需要突出显示绿色,否则为红色。如果是红色,则需要突出显示绿色。不应给用户每次单击选项以查看哪个选项正确的机会。

Html :

<label class="option"><input type="radio"  name="option" value="1" onclick="check()"/> <span id="opt1"></span></label>
    <label class="option"><input type="radio" name="option" value="2" onclick="check()" /> <span id="opt2"></span></label>
    <label class="option"><input type="radio" name="option" value="3" onclick="check()"/> <span id="opt3"></span></label>
    <label class="option"><input type="radio" name="option" value="4" onclick="check()"/> <span id="opt4"></span></label>
<button id="nextButton" class="next-btn" onclick="loadNextQuestion();">Next </button>

**Js onclick 函数**

var questions = [];
  $.ajax({
    url: 'http://127.0.0.1:8000/api/?format=json',
    type:'GET',
    async:true,
    dataType: "json",
    success: function(data)
     {
        questions = data ;
        loadQuestion();

     }
  });




function loadQuestion(){
    //questionIndex = 0
    var questionEl = document.getElementById("question");
    var opt1 = document.getElementById("opt1");
    var opt2 = document.getElementById("opt2");
    var opt3 = document.getElementById("opt3");
    var opt4 = document.getElementById("opt4");

    questionEl.innerHTML = (currentQuestion + 1) + '. '+ questions[currentQuestion].question;
    opt1.innerHTML = questions[currentQuestion].option1;
    opt2.innerHTML = questions[currentQuestion].option2;
    opt3.innerHTML = questions[currentQuestion].option3;
    opt4.innerHTML = questions[currentQuestion].option4;
  }


  var currentQuestion = 0;
  var score = 0;
  var totQuestions = 8;


function loadNextQuestion() {
  resetColor();
  var selectedOption = document.querySelector('input[type=radio]:checked');
    if(!selectedOption){
    alert('Please select your answer!' );
        return;
  }
    var answer = selectedOption.value;
    if(questions[currentQuestion].correct_answer == answer){
        score += 10;
  }

    selectedOption.checked = false;
  currentQuestion++;

  var nextButton =document.getElementById('nextButton');
    if(currentQuestion == totQuestions - 1){
        nextButton.innerHTML = 'Finish';
  }

  var container = document.getElementById('quizContainer');
  var resultCont = document.getElementById('result');

    if(currentQuestion == totQuestions){
        container.style.display = 'none';
        resultCont.style.display = '';
        resultCont.textContent = 'Your Score: ' + score;
        return;
    }
    loadQuestion(currentQuestion);
}

loadQuestion(currentQuestion);
      function check()
    {
      var selectedOption = document.querySelector('input[type=radio]:checked');
      var answer = selectedOption.value;
      if(questions[currentQuestion].correct_answer == answer)
      {
        document.getElementsByName('option').style.color="green";         
      }
      else{
        document.getElementsByName('option').style.color="red";         

          }
    }

我刚刚写了 document.getElementsByName('option').style.color="red"; ** 但没有工作,它显示错误“ **未捕获的 TypeError:无法设置未定义的属性“color”

1.那一行有什么问题。你们能帮帮我吗? 在此处输入图像描述

这是 json 对象。 在此处输入图像描述

2个回答

问题出在 document.getElementsByName('option').style.color ,因为您尝试通过标签名称获取元素,它返回所有匹配元素的数组,但 html 中没有名为 option 的元素。 假设您想显示所选答案是正确还是错误。如果正确,则文本显示绿色,如果答案错误,则显示红色。

function check()
{
  var selectedOption = document.querySelector('input[type=radio]:checked');
  var answer = selectedOption.value;
  var parentDiv = selectedOption.parentNode;
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color="green";         
  } else{
    parentDiv.style.color="red";         
  }
}

另一种简单的方法是将 id 元素附加到 label ,并将该 id 传递给 check 方法

<label class="option" id="option1">
   <input type="radio"  name="option" value="1" onclick="check(1, 'option1')"/> 
   <span id="opt1"></span>
</label>
<label class="option" id="option2">
  <input type="radio" name="option" value="2" onclick="check(2, 'option2')" /> 
  <span id="opt2"></span>
</label>
<label class="option" id="option3">
  <input type="radio" name="option" value="3" onclick="check(3, 'option3')"/> 
  <span id="opt3"></span>
</label>
<label class="option" id="option4">
  <input type="radio" name="option" value="4" onclick="check(4, 'option4')"/> 
  <span id="opt4"></span>
</label>

JS:

function check(answer, divId)
{
  var parentDiv = document.getElementById(divId);
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color = "green";         
  } else{
    parentDiv.style.color = "red";         
  }
}

更新,禁用其余单选按钮 将所有标签包装在 div 中。

<div>
<label class="option" id="option1">
   <input type="radio"  name="option" value="1" onclick="check(1, 'option1')"/> 
   <span id="opt1"></span>
</label>
<label class="option" id="option2">
  <input type="radio" name="option" value="2" onclick="check(2, 'option2')" /> 
  <span id="opt2"></span>
</label>
<label class="option" id="option3">
  <input type="radio" name="option" value="3" onclick="check(3, 'option3')"/> 
  <span id="opt3"></span>
</label>
<label class="option" id="option4">
  <input type="radio" name="option" value="4" onclick="check(4, 'option4')"/> 
  <span id="opt4"></span>
</label>
</div>
function check(answer, divId)
{
  var parentDiv = document.getElementById(divId);
  if(questions[currentQuestion].correct_answer == answer)
  {
    parentDiv.style.color = "green";         
  } else{
    parentDiv.style.color = "red";         
  }
  // additional codes to disable the other options.
  const options = parentDiv.parentNode.querySelectorAll("input[type=radio]");
  for(var i = 0; i < options.length; i++){
    options[i].disabled = true;
  }
}
Sonu Bamniya
2020-05-08

将检查函数添加到每个 radio 元素的 onchange 事件,然后将该 radio 元素作为参数传递:

<label class="option"><input type="radio" name="option" value="1" 
onchange="check(this);" /> <span id="opt1"></span></label>

然后相应地更改 javascript 函数:

function check(radio) {
resetColor();
  if (radio.checked) {
    if (questions[currentQuestion].correct_answer == radio.value) {
      radio.parentNode.style.backgroundColor = "green";
    } else {
      radio.parentNode.style.backgroundColor = "red";
    }
  } else {
    radio.parentNode.style.backgroundColor = "white";
  }
}

function resetColor() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].parentNode.style.background = "none"
  }
}

下面是我制作的一个例子,演示了您要做的事情:

var CurrentQuestion = 1;
var Answers = [3, 1, 2, 4, 3];
var AnswerStrings = ["AAA", "BBB", "CCC", "DDD"];
var done = false;

function check(radio) {
  resetColor();
  if (radio.checked) {
    if (Answers[CurrentQuestion - 1] !== parseInt(radio.value)) {
      radio.parentNode.style.backgroundColor = "red";
      //document.getElementById("answer").innerHTML = AnswerStrings[Answers[CurrentQuestion]];
      //document.getElementById("answer").style.border = "1px solid red";
    }
    showCorrect();
  } else {
    radio.parentNode.style.backgroundColor = "white";
  }
}

function showCorrect() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    if (parseInt(options[i].value) === Answers[CurrentQuestion - 1]) {
      options[i].parentNode.style.backgroundColor = "green";
    }
    options[i].setAttribute("disabled", "true");
  }
}

function resetColor() {
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].parentNode.style.background = "none"
  }
}

function resetQuestion() {
  document.getElementById("answer").innerHTML = "";
  document.getElementById("answer").style.border = "none";
  let options = document.querySelectorAll("input[name=option]");
  for (let i = 0; i < options.length; ++i) {
    options[i].removeAttribute("disabled");
    options[i].parentNode.style.background = "none"
    options[i].checked = false;
  }
}

function next() {
  resetQuestion();
  CurrentQuestion++;
  if (CurrentQuestion > Answers.length) CurrentQuestion = Answers.length;
  document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
}

function prev() {
  resetQuestion();
  CurrentQuestion--;
  if (CurrentQuestion < 1) CurrentQuestion = 1;
  document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
}

document.getElementById("Qn").innerHTML = " " + CurrentQuestion;
body {
  background-color: lightblue;
}

label{
  user-select: none;
}
<h1>Question<span id="Qn"></span></h1>

<label class="option"><input type="radio" name="option" value="1" onchange="check(this);" /> <span id="opt1">AAA</span></label>
<label class="option"><input type="radio" name="option" value="2" onchange="check(this);" /> <span id="opt2"></span>BBB</label>
<label class="option"><input type="radio" name="option" value="3" onchange="check(this);" /> <span id="opt3">CCC</span></label>
<label class="option"><input type="radio" name="option" value="4" onchange="check(this);" /> <span id="opt4">DDD</span></label>
<br/>
<p id="answer">
  <p>
    <br/>
    <input type="button" value="Prev" onclick="prev();" />
    <input type="button" value="Next" onclick="next();" />
Phillip Schulze
2020-05-08