Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery:计数复选框-计数错误_Javascript_Jquery - Fatal编程技术网

Javascript jQuery:计数复选框-计数错误

Javascript jQuery:计数复选框-计数错误,javascript,jquery,Javascript,Jquery,我有一个计数复选框的代码。选择时效果很好,但是当我取消选择一些已选择的复选框时,计数会中断(将+1添加到计数中) HTML: <div>Number of checkboxes checked: <span id='chck'>0</span></div> <table> <tr><td><input type='checkbox' /></td></tr>

我有一个计数复选框的代码。选择时效果很好,但是当我取消选择一些已选择的复选框时,计数会中断(将+1添加到计数中)

HTML:

<div>Number of checkboxes checked: <span id='chck'>0</span></div>
<table>
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr>    
</table>
$('tr :checkbox').change(function(){

    $('#chck').text($(this).add(':checked').length);

});
小提琴:

试试这个

$('#chck').text($('input[type="checkbox"]:checked').length);
    //gets all input checkboxes
或者对于具有输入的特定表,您可以这样做

$('#chck').text($(this).closest('table').find(':checked').length);
//gets all input checkboxes within the table
试试这个

$('#chck').text($('input[type="checkbox"]:checked').length);
    //gets all input checkboxes
或者对于具有输入的特定表,您可以这样做

$('#chck').text($(this).closest('table').find(':checked').length);
//gets all input checkboxes within the table

不确定为什么要使用
$(此项)。仅在
$(':checked')
时添加(':checked')
就足够了。


不确定为什么要使用
$(此项)。仅在
$(':checked')
时添加(':checked')
就足够了。

当您
选中或取消选中复选框时,计数不会自动增加,因此您需要:

$('input[type="checkbox"]').change(function(){
    $('#chck').text($('input[type="checkbox"]:checked').length);
}).change();

.

当您选中或取消选中复选框时,计数不会自动增加,因此您需要:

$('input[type="checkbox"]').change(function(){
    $('#chck').text($('input[type="checkbox"]:checked').length);
}).change();
.


“添加”用于添加元素。@马修斯:是的,我现在可以看到。我认为这是一个向现有$this添加选择器的函数。它是向现有$this添加选择器。但您最初并没有检查$this是否被选中。这就是为什么你取消选择时会被取消1。添加是为了添加一个元素。@MatthewRiches是的,我现在看到了。我认为这是一个向现有$this添加选择器的函数。它是向现有$this添加选择器。但您最初并没有检查$this是否被选中。这就是为什么当你取消选择时,你会被关闭一个。