1.补充:each
描述:一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。
.each(function(index, Element)):
描述:遍历一个jQuery对象,为每个匹配元素执行一个函数。
.each() 方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素
$.each() 是调用jQuery中的each方法 用法 如 $.each($(':checkbox'),function( ){ 注意function(i,v) 里边可以加这两个参数,代表索引,对象
与$(selector).each() 这个是调用这和个对象的each()方法 如 $(':checkbox').each(function () {
用each 方法完成反选
$('#x2').on('click',function () {
$.each($(':checkbox'),function(){
//each方法,从checkbox列表中依次取出每个checkbox对象,然后对其进行操作
console.log(this);
if ($(this).prop('checked')===false)//判断checkbox框中是否为选中,是的话就执行下一段
{
$(this).prop('checked',true);
}else{$(this).prop('checked',false);}
} );
下有重要代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--table 里边的border是特殊属性,不是style 里的, 不能直接在哪儿设置--> <table border="8"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td ><input class="c1" type="checkbox" value="1" ></td> <td>alex</td> <td>18</td> </tr> <tr> <td ><input class="c1" type="checkbox" value="2" ></td> <td>agon</td> <td>18</td> </tr> <tr> <td ><input class="c1" type="checkbox" value="3" ></td> <td>haha</td> <td>18</td> </tr> </tbody> </table> <input id="x1" type="button" value="全选" > <input id='x2' type="button" value="反选" > <input id="x3" type="button" value="取消" > <script src="../jquery-3.2.1.min.js"></script> <script> $('#x1').on('click',function () { $(':checkbox').prop('checked',true); }); // $('#x3').on('click',function () { $('.c1').val([]); 传统写法 但是一般true 或false的用prop $('#x3').on('click',function () { $(':checkbox').prop('checked',false); }); //each方法,从checkbox列表中依次取出每个checkbox对象,然后对其进行操作 // 反选方法1: $('#x2').on('click',function () { $(':checkbox').each(function () { this.checked=!this.checked; //this就是指的是当前取出的对象 // }); //下边是反选方法2 $('#x2').on('click',function () { $.each($(':checkbox'),function(){ //each方法,从checkbox列表中依次取出每个checkbox对象,然后对其进行操作 console.log(this); //this 指的是当前被each到的对像 if ($(this).prop('checked')===false){ $(this).prop('checked',true); }else{$(this).prop('checked',false);} } ); }); </script> </body> </html>