我正在学习javascript,而对于课堂作业,我正在进行一项简单的测验。在此处找到:http://redwood.colorado.edu/scho5922/dm2/projects/project1.html
我的问题是我无法让单选按钮正确验证。这可以防止计算测验分数。当您单击输入时,它会循环显示问题,但选择正确的答案不会增加分数。我通过在if语句后面添加一个警报和一个显示'score'变量的按钮来测试它。没有正确答案的警报,分数按钮(不是当前版本)显示得分为0.
的JavaScript
<script>
var beers =[
["New World Porter", "Avery"],
["Ellie's Brown Ale","Avery"] ,
["Out of Bounds Stout","Avery"] ,
["Hazed & Infused Dry Hopped Ale", "Boulder Beer"],
["Sweaty Betty Blonde Ale", "Boulder Beer"],
["Mojo IPA", "Boulder Beer"],
["Mama's Little Yellow Pils", "Oskar Blues"],
["Dale's Pale Ale", "Oskar Blues"],
["G'Knight Imperial Red Ale","Oskar Blues"],
["Old Chub Scotch Ale","Oskar Blues"]
] ;
var score = 0;
var questionNum = 0;
var turns = 0;
function enterF (beer){
questionNum++;
turns++;
var question = "What brewery makes ";
document.getElementById("header").innerHTML= question + beers[questionNum][0];
var answer = document.getElementsByName("beerbut").value.checked;
if(answers[i].checked == beers[questionNum-1][1]){
score++;
alert(score);
}
}
</script>
HTML
<body onload="popup()">
<h1 id="header">What brewery makes New World Porter</h1>
<div class="buttons">
<form>
<label for="_avery"> Avery</label>
<input type="radio" name="beerbut" id="_avery" value="Avery">
<br><br>
<label for="_bb"> Boulder Beer</label>
<input type="radio" name="beerbut" id="_bb" value="Boulder Beer">
<br><br>
<label for="_oskar"> Oskar Blues</label>
<input type="radio" name="beerbut" id="_oskar" value="Oskar Blues">
<br><br>
<label for="lefthand"> Left Hand </label>
<input type="radio" name="beerbut" id="_lefthand" value="Left Hand">
<br><br>
<input type="button" name="enter" id="enterbut" value="enter" onClick="enterF()">
</form>
</div>
</body>
</html>
答案 0 :(得分:1)
您正在尝试同时从多个元素中获取值。那不是你怎么做的。
在javascript中更改此内容
var answer = document.getElementsByName("beerbut").value.checked;
对于像这样的事情
var elements = document.getElementsByName("beerbut");
for(i = 0; i < elements.length; i++){
if(elements[i].checked){
alert(elements[i].value);
}
}