用jQuery实现反选与全选
HTML结构
<input type="checkbox" id="all"><label for="all">全选</label>
<button id="reverse">反选</button>
<ul id="list">
<li>
<input type="checkbox" id="zs"><label for="zs">张三</label>
</li>
<li>
<input type="checkbox" id="ls"><label for="ls">李四</label>
</li>
<li>
<input type="checkbox" id="mz"><label for="mz">麻子</label>
</li>
</ul>
让input状态与全选框的状态一致
$ ( '#all' ) . click ( function ( ) {
$ ( '#list input' ) . prop ( 'checked' , $ ( this ) . prop ( 'checked' ) )
} )
反选框按钮
$ ( '#reverse' ) . click ( function ( ) {
$ ( '#list input' ) . each ( function ( i, item) {
$ ( item) . prop ( 'checked' , ! $ ( this ) . prop ( 'checked' ) )
} )
chooseAll ( )
} )
每个复选框状态
$ ( '#list input' ) . on ( 'click' , function ( ) {
chooseAll ( )
} )
封装函数让复选框的状态相同
function chooseAll ( ) {
var flag = true
$ ( '#list input' ) . each ( function ( i, item) {
if ( ! $ ( item) . prop ( 'checked' ) ) {
flag = false
}
$ ( '#all' ) . prop ( 'checked' , flag)
} )
}