html
<div>
<input type="button" id="btn1" value="全选">
<input type="button" id="btn2" value="取消全选">
<input type="button" id="btn3" value="选中所有奇数">
<input type="button" id="btn4" value="选中所有偶数">
<input type="button" id="btn5" value="反选">
<br>
<input type="checkbox" name="checkbox" value="checkbox1">
checkbox1
<input type="checkbox" name="checkbox" value="checkbox2">
checkbox2
<input type="checkbox" name="checkbox" value="checkbox3">
checkbox3
<input type="checkbox" name="checkbox" value="checkbox4">
checkbox4
<input type="checkbox" name="checkbox" value="checkbox5">
checkbox5
<input type="checkbox" name="checkbox" value="checkbox6">
checkbox6
<input type="checkbox" name="checkbox" value="checkbox7">
checkbox7
<input type="checkbox" name="checkbox" value="checkbox8">
checkbox8
</div>
JQ
//ps:这里用的修改属性是prop方法,不是attr,attr适合修改自定义属性,像含有checked、selced、id等固有属性适合用prop
$('#btn1').click(function () {
$('input:checkbox').prop('checked', true);
});
$('#btn2').click(function () {
$('input:checkbox').prop('checked', false);
});
$('#btn3').click(function () {
$('input:checkbox:nth-child(odd)').prop('checked', true);
});
// 这里不是input:checkbox:odd
$('#btn4').click(function () {
$('input:checkbox:nth-child(even)').prop('checked', true);
});
$('#btn5').click(function () {
$('input:checkbox').each(function () {
/* if ($(this).prop('checked') == true) {
$(this).prop('checked', false);
} else {
$(this).prop('checked', true);
} */
$(this).prop('checked', !$(this).prop('checked'));//简化写法
});
});
需要注意的是
选中奇数行不是使用
input:checkbox:odd
而是
input:checkbox:nth-child(odd)
因为**:odd是选取索引是奇数的所有元素,索引从1开始**
如果直接用:odd过滤器的话选中索引就是13579…
而这里checkbox是按123456789,这样正常排序
相当于奇数过滤器变成了偶数。’1对应的是2,3对应的是4’
:evev同理
不过**:even选取索引是偶数的所有元素,索引从0开始**
这里就只可以使用
input:checkbox:nth-child(odd)
因为:nth-child索引下的是没有0的,是从1开始
借此在css中,我以为可以这样选中
发现根本定位不了第二个复选框
因为nth-of-type是先返回寻找前面元素,就像这里的是寻找input,
而不是input[type:checkbox]这个属性选择器,所以这里在就去定位里面自定义的2,这个索引值,发现第二个input type是button,所以就根本匹配不到了。