计数 + / - 用于复选框单击和取消单击

Count + / - for checkbox click and unclick

本文关键字:单击 取消 复选框 用于 计数      更新时间:2023-09-26

当用户单击复选框时,计数器 #counter+1,这很好,但是当他取消选中时,对于相同的复选框,它不会-1。当他们单击特定复选框和取消选中 -1 时,我想 +1。

--.JS--

$('.CheckBox').toggle(function(){
    $('#Counter').html('( '+i+' Selected )');
    i++;
}, function() {
    $('#Counter').html('( '+i+' Selected )');
    i--;
});

---.PHP---

do { ?>
<div style="position:relative; width:100%; height:20px; background-color:#FF5300;" class="CheckBox" id="<?php echo $row_EX['x1']; ?>">
<input type="checkbox" name="<?php echo $row_EX['x2']; ?>" value="<?php echo $row_EX['x3']; ?>" style="cursor:pointer; ">
<span style="position:relative; top:-2px; font-family:arial; color:#000; font-size:12px;"><?php echo $row_EX['lx4']; ?></span>
</div>
<div style="height:1px; width:1px;"></div>
<?php } while ($row_EX = mysql_fetch_assoc($EY)); ?>    
<span style="position:relative; left:10px; top:6px; font-family:arial; font-size:16px;" id="counter">(0 Selected)</span>
$('.CheckBox').change(function() {
  if (this.checked) {
    i++;
  } else {
    i--;
  }
  $('#Counter').html('( '+i+' Selected )');
});

确保在页面加载时初始化var i = 0;

尝试不同的方法:

$('.CheckBox').change(function(){
  var n_checkboxes_checked = $('.CheckBox:checked').length;
  $('#Counter').html(n_checkboxes_checked + ' Selected');
});

jsFiddle demo: http://jsfiddle.net/ENxnK/2

使用 change(),而不是 toggle()

var i = 0;
$('.CheckBox').change(function() {
    if ( $(this).attr('checked') ) {
        i++;
    } else {
        i--;
    }
    $('#Counter').html('( ' + i + ' Selected )');
});

您没有任何代码可以处理单击此处的复选框。 jquery中的.toggle只处理隐藏/显示元素。

我认为你不需要像其他人建议的那样遍历所有.checkbox元素......你也不需要全局变量i。而是像

$('.CheckBox input').click(function(){
    $('#Counter').html('( '+$('.CheckBox input:checked').length()+' Selected )');
}

在jQuery文档中它说....

    Description: Bind two or more handlers to the matched elements, to be executed on alternate clicks.
.toggle( handler(eventObject), handler(eventObject) [, handler(eventObject)] )
handler(eventObject)A function to execute every even time the element is clicked.
handler(eventObject)A function to execute every odd time the element is clicked.

所以它与检查/取消选中

无关

这样做

$('.CheckBox').click(function(){
    if($(this).attr('checked')){
        $('#Counter').html('( '+i+' Selected )');
        i++;
    }else{
        $('#Counter').html('( '+i+' Selected )');
        i--;    
    }
}

是的,单击而不是切换...我错过了,你不习惯使用 attr