.checked不起作用

时间:2014-03-16 16:19:50

标签: jquery html

我有以下代码:http://jsfiddle.net/TXQ9U/37/(请参阅下面的代码)

我想要实现的是,我按下提交按钮,我弹出一个说答案是正确的或答案不正确并添加一个分数。我想我已经把它设置得正确但是没有让它运转起来。有什么建议吗?

亲爱的,

Marc

HTML:

<body>

<p> Question 1: what sport does Roger Federed play? </p>
<table width = "200">

    <tr>
        <td> <input type="radio" name="radio" class="a1" value="a1" /> Cricket </td>
        <td> <input type="radio" name="radio" class="a2" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a3" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a4" value="a1" /> Tennis </td>
    </tr>

</table>

  <button  class="button1"> Submit </button>
<button class ="button2"> Next page</button>


</body>

的jQuery

var score= 0;

function submit(){
       var correctanswer = document.getElementById("a2")
       if(correctanswer.checked === true) {
              score++;
              alert("Answer is correct" + score)               
} 
else {
            alert("Answer is not correct")
}
}    


$(".button1").on("click",function(){
alert(submit());
});

2 个答案:

答案 0 :(得分:3)

您没有ID为a2的元素,这是一个类,因此getElementById失败了 因为你已经在使用jQuery了,你可以做到

function submit() {
    var correctanswer = $(".a2");
    if (correctanswer.is(':checked')) {
        return "Answer is correct";
    } else {
        return "Answer is not correct";
    }
}

FIDDLE

答案 1 :(得分:0)

因为你正在使用jQuery:

<body>
    <script type="text/javascript">
        var score = 0;
        $(document).ready(function() {
            $(".button1").on("click", function () {
                submit();
            });
        });

        function submit() {
            var correctanswer = $("#a2");
            if (correctanswer.is(":checked")) {
                score++;
                alert("Answer is correct" + score);
            }
            else {
                alert("Answer is not correct");
            }
        }
    </script>

    <p> Question 1: what sport does Roger Federed play? </p>
    <table width="200">

        <tr>
            <td> <input type="radio" name="radio" id="a1" value="a1" /> Cricket </td>
            <td> <input type="radio" name="radio" id="a2" value="a1" /> Tennis </td>
            <td> <input type="radio" name="radio" id="a3" value="a1" /> Baseball </td>
            <td> <input type="radio" name="radio" id="a4" value="a1" /> Basketbakk </td>
        </tr>

    </table>

    <button class="button1"> Submit </button>
    <button class="button2"> Next page</button>


</body>