此示例有效但给出了“未捕获的TypeError:无法读取属性'已检查'未定义”
但不适用于&&两个if语句的属性
if(x == true)&&如果(j == “正确”)
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>
答案 0 :(得分:2)
使用OP_NO_TLSv1
代替i< options.length
因为options.length是2.如果你使用i<=options.length
那么它会迭代到=<
所以你2是未定义的。< / p>
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";
}
}
}
};