检查单选按钮时jquery关于小分析的问题

时间:2010-04-26 21:03:25

标签: jquery radio-button

的jQuery

$(function() {

       var service1price = 1;
       var service2price = 2;

       $("#service1checked").one('click', function() {
                                    $('<div id="service1ok"> Service Number 1, ' + service2price + ' $ </div>').fadeIn().appendTo('.selecteditems');
           });

       $("#service2checked").one('click', function() {
                                    $('<div id="service2ok"> Service Number 2, ' + service1price + ' $ </div>').fadeIn().appendTo('.selecteditems');
           });


       $("#service1no").one('click', function() {
                                    $('#service1ok').fadeOut();
           });

       $("#service2no").one('click', function() {
                                    $('#service2ok').fadeOut();
           });

$("#service1checked").one('click',function() {
                                   $('<div id="service1okprice">' + service1price + '</div>').fadeIn().appendTo('.totalcost');
                                   });
$("#service2checked").one('click',function() {
                                   $('<div id="service2okprice">' + service2price + '</div>').fadeIn().appendTo('.totalcost');
                                   });
       });

HTML:

<div id="left">
<form>
<p>service 1</p><p class="red">Price 1 $</p>
Yes<input type="radio" name="service1" value="service1yes" id="service1checked" />
No<input type="radio" name="service1" value="service1no" id="service1no" />


<p>service 2</p><p class="red">Price 2 $</p>
Yes<input type="radio" name="service2" value="service2yes" id="service2checked" />
No<input type="radio" name="service2" value="service2no" id="service2no" />
<br />
<input type="submit">
</form><br />
</div>
<div id="center">

<div class="selecteditems">
Selected Items:
</div>

<div class="totalcost">
Total cost:
</div>

</div>

我如何总结变量,当选中单选按钮并以总成本div显示时,例如,如果选择了2个单选框,那么将会出现以下情况:总成本:3 $。

1 个答案:

答案 0 :(得分:0)

如果你制作了一个通用的点击处理程序,而不是为每次点击制作一个特定的处理程序。为您的所有单选按钮提供一类“服务”或类似的东西。然后做这样的事情:

var total = 0

$(".services").click( function() {
   recalc()
})

function recalc() {
    if($('#service1checked').checked) {
         $('<div id="service1ok"> Service Number 1, ' //....etc..
         total = total + 1    
    }

    // other conditions ...

    $('#totalcost').html(total)
}