选中或取消选中所有启用的复选框

问题描述:

我试图在点击'#leg-chkAll'时切换所有启用的复选框,但是 我错过了一些东西!选中或取消选中所有启用的复选框

如果可能,请解释一下javascript代码。

$(document).ready(function(){ 
 
    $('#leg-chkAll).on('click', function() { 
 
\t \t $('div#legend').find('div :checkbox:enabled') \t \t \t \t \t 
 
\t \t \t .prop('checked', this.checked) 
 
\t \t \t .find('tbody :checkbox').toggleClass('selected', this.checked); 
 

 
\t }); 
 
});
<div id="leg-chkAll"> 
 
    <input type="checkbox"> 
 
    <span class="leg-des">All</span> 
 
</div> 
 
<div id="legend"> 
 
    <div id="leg-evt1"> 
 
     <input type="checkbox" class="leg-chk" checked> 
 
     <span class="leg-cod ev-event1">E1</span> 
 
     <span class="leg-des">Event1</span> 
 
     <span class="leg-day">1</span> 
 
    </div> 
 
    <div id="leg-evt2"> 
 
     <input type="checkbox" class="leg-chk" checked> 
 
     <span class="leg-cod ev-event2">E2</span> 
 
     <span class="leg-des">Event2</span> 
 
     <span class="leg-day">10</span> 
 
    </div> 
 
    <div id="leg-evt3"> 
 
     <input type="checkbox" class="leg-chk" checked> 
 
     <span class="leg-cod ev-event3">E3</span> 
 
     <span class="leg-des">Event3</span> 
 
     <span class="leg-day">3</span> 
 
    </div> 
 
    <div id="leg-evt4"> 
 
     <input type="checkbox" class="leg-chk" disabled> 
 
     <span class="leg-cod ev-event4">E4</span> 
 
     <span class="leg-des">Event4</span> 
 
     <span class="leg-day">0</span> 
 
    </div> 
 
    <div id="leg-evt5"> 
 
     <input type="checkbox" class="leg-chk" checked> 
 
     <span class="leg-cod ev-event5">E5</span> 
 
     <span class="leg-des">Event5</span> 
 
     <span class="leg-day">6</span> 
 
    </div> 
 
</div>

问候, 埃利奥·费尔南德斯

两个问题:

  1. 它看起来像你只是在这里失踪的关单引号:$('#leg-chkAll)

  2. #leg-chkAll是第一个div的id,但您希望听取第一个复选框的点击,而不是包含div。

如果您将该id放在复选框元素上,它会起作用。 HTML的第一个块更改为:

<div> 
    <input type="checkbox" id="leg-chkAll" checked> 
    <span class="leg-des">All</span> 
</div> 

然后修改您的jQuery像这样:

$(document).ready(function(){ 
    $('#leg-chkAll').on('click', function() { 
    $('#legend').find(':checkbox:enabled').prop('checked', this.checked) 
    }); 
}); 

这里有一个工作的jsfiddle:https://jsfiddle.net/t9w944z9/

+1

谢谢,工作得很好。 –