代碼需求, 使用attr只能執行一次,使用prop則完美實現全選和反選,獲取所有選中的項並把選中項的文本組成一個字符串。
解決方案一:
代碼如下:
<html>
<head>
<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
</head>
<body>
<input type="checkbox" name="chk_list[]" value="1" />1
<input type="checkbox" name="chk_list[]" value="2" />2
<input type="checkbox" name="chk_list[]" value="3" />3
<input type="checkbox" name="chk_list[]" value="4" />4
<input type="checkbox" name="chk_all" id="chk_all" />全選/取消全選
<script type="text/javascript">
$("#chk_all").click(function(){
// 使用attr只能執行一次
$("input[name='chk_list[]']").attr("checked", $(this).attr("checked"));
// 使用prop則完美實現全選和反選
$("input[name='chk_list[]']").prop("checked", $(this).prop("checked"));
// 獲取所有選中的項並把選中項的文本組成一個字符串
var str = '';
$($("input[name='chk_list[]']:checked")).each(function(){
str += $(this).next().text() + ',';
});
alert(str);
});
</script>
</body>
</html>
總結:
對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法。
參考 http://www.jb51.net/article/62308.htm
<script type="text/javascript">
jQuery(function($) {
// 給全選添加點擊事件
$("[name='allSel']").click(function(){
if($(this).is(':checked')){
$("[name='select']").prop('checked',true);
}else{
$("[name='select']").prop('checked',false);
}
});
//給復選框添加點擊事件
$("[name='select']").click(function(){
var allSel = false;
$("[name='select']").each(function(){
if(!$(this).is(':checked')){
allSel = true;
}
})
//如果有checkbox沒有被選中
if(allSel){
$("[name='allSel']").prop('checked',false);
}else{
$("[name='allSel']").prop('checked',true);
}
})
});
</script>
