&安培;&安培; not working and Uncaught TypeError:无法读取未定义的属性'checked'

时间:2017-07-02 05:54:41

标签: javascript bitwise-operators

此示例有效但给出了“未捕获的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>

1 个答案:

答案 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";	
				}
			}		
		}
	};