0

我正在制作一个交互式清单,该清单需要计算用户选择了多少“是”和“否”答案,并在警报框或页面上显示总数。是答案的值为 1,否的答案值为 0。

问题是,当我单击总计按钮时,它会显示每个答案的值,然后是总计 - 我只需要它来显示总计。

我一直在寻找解决方案,并根据我已经找到的内容修改了我的代码。我对javascript很陌生,所以我一定遗漏了一些东西。

这是代码:

    <script type="text/javascript"><!--
    $(document).ready(function () {
    $('input:radio').on('change',function(){
    var $first_question = parseInt($("input[name=first_answer]:checked").val());
    var $second_question = parseInt($("input[name=second_answer]:checked").val());
    $first_question = $first_question? $first_question : 0; 
    $second_question = $second_question? $second_question : 0;

    var $total_score = $first_question + $second_question;


   {
   $("#btn").click(function() {
   alert($total_score);
   });
   };

   });
   });
   //--></script>

这是我的 HTML:

    <p id="first_question">First Question<input name="first_answer" class="styled"    type="radio" value="1" /><!-- POSITIVE ANSWER -->Yes <input name="first_answer" class="styled" type="radio" value="0" /><!-- NEGATIVE ANSWER -->No</p>
    <p id="second_question">second question <input name="second_answer" class="styled" type="radio" value="1" /><!-- POSITIVE ANSWER -->Yes <input name="second_answer" class="styled" type="radio" value="0" /><!-- NEGATIVE ANSWER -->No</p>
    <input id="btn" type="button" value="See total" /> <input type="reset" value="Reset" /></body>
4

1 回答 1

0

这是想要的吗?

var $total_score = 0;

$(document).ready(function () {
    $('input:radio').on('change',function(){
        var $first_question = parseInt($("input[name=first_answer]:checked").val());
        var $second_question = parseInt($("input[name=second_answer]:checked").val());
        $first_question = $first_question? $first_question : 0; 
        $second_question = $second_question? $second_question : 0;
        $total_score = $first_question + $second_question;
    });

   $("#btn").click(function() {
       alert($total_score);
    });

});

如果是,则您的错误是每次单选按钮更改值时都向单击按钮添加了一个事件。

于 2013-08-07T15:35:31.837 回答