0

我编写了这个脚本来检查何时选择了“A”、“B”和“C”类的复选框,然后将它们添加在一起(这些类被分配给多个复选框)。但是,我只想计算它们被检查的一个实例,而这个脚本每次检查具有这些值的复选框时都会计算它们。我怎样才能改变它只计算一次?

jQuery:

 $(function() {
        $('#product-counter .counter').text('0');

        var total = $("#search-id-checkboxes .A:checked").length + $("#search-id-checkboxes .B:checked").length + $("#search-id-checkboxes .C:checked").length;
        if(total>0){$("#product-counter .counter").text(total);}
        else{$("#product-counter .counter").text('0');}
    })

    function updateCounter() {
        var len = $("#search-id-checkboxes .A:checked").length + $("#search-id-checkboxes .B:checked").length + $("#search-id-checkboxes .C:checked").length;
        if(len>0){$("#product-counter .counter").text(len);}
        else{$("#product-counter .counter").text('0');}
    }

    $("#search-id-checkboxes input:checkbox").on("change", function() {
        updateCounter();
    });

html:

<div id="search-id-checkboxes">
<input type="checkbox" class="A"/> A<br />
<input type="checkbox" class="A" /> A<br />
<input type="checkbox" class="B" /> B<br /> 
<input type="checkbox" class="B" /> B<br /> 
<input type="checkbox" class="C" /> C<br /> 
<input type="checkbox" class="C" /> C<br />   
</div>
4

3 回答 3

0

即兴逻辑没有迭代并处理内部计算的总数,

演示:http: //jsfiddle.net/MQhyt/

全功能:

$(function () {
    $('#product-counter .counter').text('0');

    var inArray = [];
    $("#search-id-checkboxes :checkbox").each(function () {
        if (this.checked && $.inArray(this.className, inArray) == -1) {
            inArray.push(this.className);
        }
    });

    var total = inArray.length;

    if (total > 0) {
        $("#product-counter .counter").text(total);
    } else {
        $("#product-counter .counter").text('0');
    }
    $("#search-id-checkboxes input:checkbox").on("change", function () {
        updateCounter.call(this);
    });

    function updateCounter() {
        var elClass = this.className;
        var $el = $('#search-id-checkboxes .' + elClass + ':checked');

        if ($el.length == 1 && this.checked) {
            total += 1;
        } else if ($el.length == 0) {
            total -= 1;
        }

        $("#product-counter .counter").text(total);
    }
});

如果您对上述逻辑有任何问题,请查看此版本http://jsfiddle.net/WLmtq/ 。.each


可能你想像下面这样检查,

var len = ($("#search-id-checkboxes .A").is(":checked") ? 1 : 0) + 
          ($("#search-id-checkboxes .B").is(":checked") ? 1 : 0) + 
          ($("#search-id-checkboxes .C").is(":checked") ? 1 : 0);

演示:http: //jsfiddle.net/MCKtA/

于 2013-05-17T19:57:23.630 回答
0

你已经尝试过jquery的独特方法了吗?见http://api.jquery.com/jQuery.unique/

于 2013-05-17T19:52:29.700 回答
-1

用这个...

var total = 0;
$(':checkbox').on('change', function (e) {
    var a = $(this).prop('class');
    if($("." + a + ':checked').length == 1 && $(this).is(':checked')){
        total +=1;
    }
    if($("." + a + ':checked').length == 0){
        total-=1;
    }
    $('#product-counter .counter').text(total);
});

看这个演示

于 2013-05-17T20:03:50.507 回答