javascript - CheckAll/UncheckAll 复选框与 jQuery

标签 javascript jquery html

我做了一个复选框checkall/uncheckall。

HTML

<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>

主要.js

function checkAll(parentId,allClass,checkboxClass,allChecked){
    checkboxAll = $('#'+parentId+' .'+allClass);
    otherCheckBox = $('#'+parentId+' .'+checkboxClass);
    checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
    if(allChecked=='false'){
        if(otherCheckBox.size()==checkedCheckBox.size()){
            checkboxAll.attr('checked',true);
        }else{
            checkboxAll.attr('checked',false);
        }
    }else{
        if(checkboxAll.attr('checked')){
            otherCheckBox.attr('checked',true);
        }else{
            otherCheckBox.attr('checked',false);
        }
    }
}

它工作正常。但是当我有很多复选框时会变得笨重。我想通过使用 jQuery 而不是在每个复选框上放置 onchange 来完成同样的工作。我尝试了不同种类的东西,但无法工作。我尝试了以下一个:

$('.check input[type="checkbox"]').change(function(e){
    checkAll('selectCheckBox','all','check','true');
});

做与 onchange 事件相同的工作,但没有工作。我哪里出错了。

最佳答案

我认为您只需要这个:您不需要传递所有参数并附加内联 onchange 事件。您可以简化代码。

$(function () {
    $('input[type="checkbox"]').change(function (e) {
       if(this.className == 'all')
       {
           $('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
       }
        else
        {
            $('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
        }
    });
});

Demo

关于javascript - CheckAll/UncheckAll 复选框与 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875433/

相关文章:

javascript - 循环div?

javascript - Chrome 扩展 : URL not opening in new tab

javascript - D3中选择多个元素添加单父节点

javascript - 将常规 amChart 设置存储为变量并在函数中重复使用它

javascript - 带有百分比的图像大小会减慢网站速度

javascript - View 不使用数据呈现

javascript - React-Apollo : Could not find "client" in the context or passed in as an option

html - 将 HTML 转换为 markdown

HTML 内联 block 不直吗?

css - 3 列 + 100% 高度