【问题标题】:.attr('checked') will not tell me that the radio button is checked even when it is.attr('checked') 不会告诉我单选按钮已被选中,即使它是
【发布时间】:2014-06-25 16:52:14
【问题描述】:

我的第一个问题!...我是一名大学生,正在尝试做一个简单的多项选择测验。我几乎完成了它(它的骨架),但无法计算用户的最终分数。测验可以在线查看:eyeballs.site88.net(这只是测验,所以没有其他分散注意力的代码)。

我认为这种方法很简单:
1.从0分开始。
2.当用户点击“答案”按钮时,(对于每个问题)检查是否选中了正确答案旁边的单选按钮
3.如果是,加1分
4. 如果不是,什么都不做
5.最后一题检查完毕后,向用户公布分数

除了 .attr('checked') 部分之外,所有代码似乎都可以正常工作。我用 .val() 替换了它,分数加起来很好,最后宣布了。但是,即使检查了正确的答案,分数也不会加 1。我之前看过 .attr('checked') - 它检查是否选中了“与上面相同”复选框:如果选中,则 div 滑出视图;如果未选中,则 div 会滑回视图中。但我什么也做不了!

下面的代码是一个简化版(只是问题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 控制台没有显示任何错误!

【问题讨论】:

  • 只是好奇 - $questionAndAnswer 是在哪里定义的?
  • 顺便说一句,this 会给你它不工作的原因
  • 抱歉,我是新手(很紧张!)。我刚刚编辑了问题以包含您质疑的变量。它在原始代码中。 :)
  • Np,请检查我提供的链接,它会告诉您为什么 .attr() 不起作用,但 .prop() 会。

标签: jquery radio-button attr checked


【解决方案1】:

你可以改用:

if($('#question1answerA').prop('checked'))

【讨论】:

  • prop 在这里返回一个布尔值:与true 比较是没有意义的。
  • 我尝试了 .prop('checked') 并且效果很好!我以前没有听说过这个功能(我是 jQuery 新手)。你能告诉我为什么它有效吗?根据我的教科书 .attr('checked') 应该可以工作(教科书中有一个示例,但使用的是复选框,而不是单选按钮)。 :)
  • 您尝试使用名为“checked”的自定义属性,但在 radio 元素中不存在。希望它有所帮助:)
  • @Alexandros 非常感谢!我想“接受”您的回答,但不知道该怎么做!.....编辑:刚刚想通了!我第一个问题的胜利,谢谢你!
【解决方案2】:

其他方式判断是否勾选

$('#question1answerA')[0].checked

$('#question1answerA:checked').length

$('#question1answerA').is(':checked')

【讨论】:

  • 这些建议有点过头了,因为我是新手,但我一定会去看看!谢谢:)
猜你喜欢
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 2022-11-15
  • 2020-03-27
  • 2020-11-05
  • 2020-07-28
  • 2015-06-30
  • 2018-08-24
相关资源
最近更新 更多