問題:工作中要用到jQuery操作多選框(checkbox)的知識,就把以前記錄及筆記找了出來直接用,但是問題出現了,取消選擇之後,再次選中指定的多選框,用瀏覽器看(F12)是加上了checked屬性,但是頁面顯示沒有選中(沒有打勾),這裏把解決問題的方法總結一下。
下面給出一種解決方案(使用的jQuery版本2.1.3):
1、靜態頁面CheckBox.html(注意:必須要在check標籤裏面加上select屬性)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery操作ChecBox的用法</title>
<script type="text/javascript" src="js/jquery.min.js" ></script>
<script type="text/javascript" src="js/CheckBox.js" ></script>
</head>
<body>
<input type="checkbox" name="checkBox1" value="1" checked="true">1</input>
<input type="checkbox" name="checkBox1" value="2" checked="true">2</input>
<input type="checkbox" name="checkBox1" value="3" checked="true">3</input>
<input type="checkbox" name="checkBox1" value="4" checked="true">4</input>
<input type="checkbox" name="checkBox1" value="5" checked="true">5</input>
<input type="checkbox" name="checkBox1" value="6" checked="true">6</input>
<input type="checkbox" name="checkBox1" value="7" checked="true">7</input>
<input type="checkbox" name="checkBox1" value="8" checked="true">8</input>
<input type="checkbox" name="checkBox1" value="9" checked="true">9</input>
</body>
<div>
<input type="button" value="全選"/ onclick="selectAll()">
<input type="button" value="反選" onclick="fanXuan()"/>
<input type="button" value="取消選擇" onclick="cancelSelect()"/>
</div>
</html>
2、js文件 多選、取消選擇和反選(CheckBox.js)
function selectAll(){
$("input[name='checkBox1']").each(function(){
$(this).prop("checked",true);
});
}
function fanXuan(){
$("input[name='checkBox1']").each(function(){
if($(this).prop("checked") == true){
$(this).prop("checked",false);
}else{
$(this).prop("checked",true);
}
});
}
function cancelSelect(){
$("input[name='checkBox1']").each(function(){
$(this).prop("checked",false);
});
}
這裏使用的時prop屬性,下面分析一下原因,爲了避免重造輪子,大家可以到下面兩篇文章看一下:
參考文章1:jquery中attr和prop的區別
參考文章2:jquery中attr方法和prop方法的區別