&&&不起作用和未捕获的类型错误:无法读取未定义的属性'checked'



此示例有效,但给出"未捕获的类型错误:无法读取未定义的属性'checked'

"但不适用于两个 &&属性 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>

最新更新