我的第一个问题!...我是一名大学生,正在尝试做一个简单的多项选择测验。我几乎完成了它(它的基本框架),但无法计算用户的最终分数。该测验可以在线查看:eyeballs.site88.net (这只是测验,因此没有其他分散注意力的代码)。
我认为这种方法很简单:
1. 从 0 分开始。
2. 当用户单击“答案”按钮时,(对于每个问题)检查正确答案旁边的单选按钮是否被选中
3.如果是,则分数加1
4. 如果不是,则不执行任何操作
5.最终题核对完毕后,向用户公布分数
除了 .attr('checked') 部分之外,所有代码似乎都工作得很好。我用 .val() 替换了它,分数加起来就很好,并在最后宣布。然而,即使检查出正确答案,分数也不会加1。我之前见过 .attr('checked') 的作用 - 它检查是否选中了“与上面相同”复选框:如果选中,则 div 滑出 View ;如果未选中,则 div 会滑回到 View 中。但我无法让任何事情发生!
下面的代码是一个简化版本(只是问题1,只有2个答案选择):
HTML
<form action=”xxxxx” method=”post” class=”quiz”>
<ul>
<li class="quizQuestionAndAnswer" id="question1" >
<dl>
<dt class="quizQuestion"><strong>1. An animal with horizontal, rectangular pupils is a:</strong>
</dt>
<dd class="quizAnswers">
<div>
<input type="radio" name="question1Answer" id="question1answerA" value="goat" >
<label for="question1answerA">goat</label>
</div>
<div>
<input type="radio" name="question1Answer" id="question1answerB" value="elephant" >
<label for="question1answerB">elephant</label>
</div>
</dd>
</dl><!--end question1-->
</li>
</ul>
</form>
JavaScript
<script>
$(document).ready(function() {
var score=0,
$questionAndAnswer=$('.quizQuestionAndAnswer');
$questionAndAnswer.on('click', '.answersQuizButton', function() {
if( $('#question1answerA').attr('checked') ) {
score=score+1;
} //end if
if( $('#question2answerC').attr('checked') ) {
score=score+1;
} //end if
alert(score);
}); //end on (click)
}); //end ready
</script>
如果有任何建议,我将非常感激! :) uphillfun ps:我使用的是 jQuery 1.11.0,Firebug 控制台没有显示任何错误!
最佳答案
您可以使用:
if($('#question1answerA').prop('checked'))
关于jquery - .attr ('checked' )不会告诉我单选按钮已被选中,即使它是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23539358/