&& not working and Uncaught TypeError: Cannot read property 'checked' of undefined

&& not working and Uncaught TypeError: Cannot read property 'checked' of undefined

此示例有效但给出 "Uncaught TypeError: Cannot read property 'checked' of undefined"

但不适用于 && 属性 两个 if 语句

if(x == true) && if(j=="correct")

 function myFunction(){

  var question = document.getElementById("question-1");
  var options = question.getElementsByTagName("input");
  
  for(var i=0;i<=options.length;i++){
   
   var x = options[i].checked;
   var j = options[i].className;
      // if(x == true) && if(j=="correct"){ - this does not work
   if(x == true){
    if(j=="correct"){
     question.getElementsByClassName("result")[0].innerHTML = "Your answer is correct"; 
    }else{
     question.getElementsByClassName("result")[0].innerHTML = "Your answer is wrong"; 
    }
   }  
  }
 };
 <ul>
  <div id="question-1">
   <li>What is a Computer Bug?</li>
   <input type="radio" name="selection" class="correct" onclick="myFunction()"><label>An error</label>
   <input type="radio" name="selection" class="wrong" onclick="myFunction()"><label>A Moth</label> 
   <p class="result"></p>
  </div>
 </ul>

使用 i< options.length 而不是 i<=options.length 因为 options.length 是 2。如果你使用 =< 那么它将迭代到 2<=2 所以你 2未定义。

function myFunction(){

  var question = document.getElementById("question-1");
  var options = question.getElementsByTagName("input");
 
  for(var i=0;i<options.length;i++){
   
   var x = options[i].checked;
   var j = options[i].className;
      // if(x == true) && if(j=="correct"){ - this does not work
   if(x == true){
    if(j=="correct"){
     question.getElementsByClassName("result")[0].innerHTML = "Your answer is correct"; 
    }else{
     question.getElementsByClassName("result")[0].innerHTML = "Your answer is wrong"; 
    }
   }  
  }
 };
<ul>
  <div id="question-1">
   <li>What is a Computer Bug?</li>
   <input type="radio" name="selection" class="correct" onclick="myFunction()"><label>An error</label>
   <input type="radio" name="selection" class="wrong" onclick="myFunction()"><label>A Moth</label> 
   <p class="result"></p>
  </div>
 </ul>