jquery 实现全选,反选,全不选等功能,下面直接以例子进行说明。
设页面有如下一组复选框和几个相关按钮(全选,反选,全不选等):
01 | < input type = "checkbox" name = "fruit" value = "apple" />苹果 |
02 | < input type = "checkbox" name = "fruit" value = "orange" />橘子 |
03 | < input type = "checkbox" name = "fruit" value = "banana" />香蕉 |
04 | < input type = "checkbox" name = "fruit" value = "grape" />葡萄 |
05 |
06 | < input type = "button" id = "btn1" value = "全选" > |
07 | < input type = "button" id = "btn2" value = "全不选" > |
08 | < input type = "button" id = "btn3" value = "反选" > |
09 | < input type = "button" id = "btn4" value = "选中所有奇数" > |
10 | < input type = "button" id = "btn5" value = "获得选中的所有值" > |
则分别实现相关功能的完整代码如下:
01 | $( function (){ |
02 | $( '#btn1' ).click( function (){ //全选 |
03 | $( "[name='fruit']" ).attr( 'checked' , 'true' ); |
04 | }); |
05 | $( '#btn2' ).click( function (){ //全不选 |
06 | $( "[name='fruit']" ).removeAttr( 'checked' ); |
07 | }); |
08 | $( '#btn3' ).click( function (){ //反选 |
09 | $( "[name='fruit']" ).each( function (){ |
10 | if ($( this ).attr( 'checked' )){ |
11 | $( this ).removeAttr( 'checked' ); |
12 | } else { |
13 | $( this ).attr( 'checked' , 'true' ); |
14 | } |
15 | }) |
16 | }); |
17 | $( "#btn4" ).click( function (){ //选中所有奇数 |
18 | $( "[name='fruit']:even" ).attr( 'checked' , 'true' ); |
19 | }) |
20 | $( "#btn5" ).click( function (){ //获取所有选中的选项的值 |
21 | var checkVal= '' ; |
22 | $( "[name='fruit'][checked]" ).each( function (){ |
23 | checkVal+=$( this ).val()+ ',' ; |
24 | }) |
25 | alert(checkVal); |
26 | }) |
27 | }); |
注意使用 jquery 之前必须要引入 jquery 包哦!