本文內(nèi)容比較簡單卻很常用,主要講述使用jQuery的選擇器實現(xiàn)全選、全不選(兩種方法實現(xiàn))及反選(兩種方法實現(xiàn))的效果。
效果圖:
全選、全不選及反選效果.gif
詳情見文中代碼注釋。
代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//全選
$("#qx").click(function(){
$("#che :checkbox").prop('checked',true);
})
//全不選
$("#qbx").click(function(){
//使用prop將checked屬性改為false(建議),或者刪除checked屬性(不建議)。
$("#che :checkbox").prop('checked',false);//方法一:將checked屬性改為false
// $("#che :checkbox").removeProp('checked');//方法二:刪除checked屬性
})
//反選方法一:先得到已經(jīng)被選擇的對象,然后全選,再將之前被選擇的對象刪除checked屬性
// $("#fx").click(function(){
// var yx = $("#che :checked");
// $("#che :checkbox").prop('checked',true);
// yx.removeProp('checked');
// })
// 反選方法二:
// prop(‘checked’,函數(shù)(參數(shù)一,參數(shù)二));函數(shù)是用來設置當前屬性(checked)的屬性值的,里面兩個參數(shù),可設為i,val。
// i代表當前元素序號,val代表當前屬性的屬性值。
$("#fx").click(function(){
$("#che :checkbox").prop('checked',function(i,val){
return !val;//返回當前屬性值相反的值
})
})
})
</script>
</head>
<body>
<input type="button" id="qx" value="全選" />
<input type="button" id="qbx" value="全不選" />
<input type="button" id="fx" value="反選" />
<br /><br />
<table id="che">
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>好好學習,天天向上</td>
</tr>
</table>
</body>
</html>
如有問題歡迎交流。
如轉(zhuǎn)載請注明出處,謝謝!