爱好选择器 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html > <head > <meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" > <title > 全选练习</title > </head > <body > <form > 你爱好的运动是?<input type ="checkbox" id ="checkedAllBox" /> 全选/全不选 <br /> <input type ="checkbox" name ="items" value ="足球" /> 足球 <input type ="checkbox" name ="items" value ="篮球" /> 篮球 <input type ="checkbox" name ="items" value ="羽毛球" /> 羽毛球 <input type ="checkbox" name ="items" value ="乒乓球" /> 乒乓球 <br /> <input type ="button" id ="checkedAllBtn" value ="全 选" /> <input type ="button" id ="checkedNoBtn" value ="全不选" /> <input type ="button" id ="checkedRevBtn" value ="反 选" /> <input type ="button" id ="sendBtn" value ="提 交" /> </form > <script type ="text/javascript" src ="jquery-1.10.1.js" > </script > <script type ="text/javascript" > var $checkedAllBox = $('#checkedAllBox' ) var $items = $(':checkbox[name=items]' ) $('#checkedAllBtn' ).click(function ( ) { $items.prop("checked" ,true ) $checkedAllBox.prop("checked" ,true ) }) $('#checkedNoBtn' ).click(function ( ) { $items.prop("checked" ,false ) $checkedAllBox.prop("checked" ,false ) }) $('#checkedRevBtn' ).click(function ( ) { console .log("反选" ) $items.each(function () { this .checked = !this .checked }) $checkedAllBox.prop("checked" , $items.not(':checked' ).length === 0 ) }) $('#sendBtn' ).click(function ( ) { $items.filter(':checked' ).each(function () { console .log(this .value) }) }) $('#checkedAllBox' ).click(function ( ) { $items.prop("checked" ,this .checked) }) $items.click(function () { $checkedAllBox.prop('checked' ,$items.not(':checked' ).length===0 ) }) </script > </body > </html >
总结
对于反选与更新状态部分的,实则算是一个监听,监听当前复选框组合中,未被选中的有多少个,来判定更改全选/全不选的选中状态