3

チェックボックスのチェックオール/チェックオール解除を行いました。

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>

main.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);
        }
    }
}

それは正常に動作します。しかし、チェックボックスがたくさんあると、かさばります。各チェックボックスにonchangeを配置するのではなく、jQueryを使用して同じ作業を行いたいです。さまざまなことを試しましたが、うまくいきませんでした。私は次のものを試しました:

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

onchange イベントと同じように動作しますが、動作しませんでした。どこで間違ったのですか。

4

3 に答える 3

2

これだけが必要だと思います。すべての引数を渡して、インラインの 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.
        }
    });
});

デモ

于 2013-06-01T17:54:40.560 に答える
1

セレクターが間違っています:

.check input[type="checkbox"]

checkbox上記は、クラスを持つ祖先を持つタイプの入力を選択します.check。これは次のように一致します。

<div class="check">
    <input type="checkbox".../> 
</div>

そのはず:

input.check[type="checkbox"]
于 2013-06-01T17:47:35.597 に答える
0

$('.check input[type='checkbox']')代わりにここで文字列を閉じました。二重引用符を使用する必要があります$('.check input[type="checkbox"]')

于 2013-06-01T17:46:03.137 に答える