<script type="text/javascript">
function check(){
var inputList = document.getElementsByName("product");
for(var i=0;i<inputList .length;i++){
inputList [i].checked = document.getElementById("all").checked;
}
}
</script>
</head>
<body>
全選<input id="all" type="checkbox" value="全選" onclick="check()">
<hr>
<input name="product" type="checkbox" value="1">
<input name="product" type="checkbox" value="2">
<input name="product" type="checkbox" value="3">
</body>
在check()函數中,獲取所有name爲product的複選框,並保存在數組inputList中,然後使用getElementById()方法獲取id爲all的“全選”複選框,並獲取其checked屬性值,在循環遍歷時,將這個值賦給每個複選框的checked屬性。
//以下用jquery實現
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#all").click(function(){
$(".v").prop("checked",$(this).is(':checked'));
//$(".v").attr("checked",$(this).is(":checked"));區別看下面
});
});
</script>
</head>
<body>
全選<input type="checkbox" id="all">
a<input type="checkbox" class="v">
b<input type="checkbox" class="v">
c<input type="checkbox" class="v">
</body>
attr和prop區別:
舉一個例子:
<input id="chk1" type="checkbox" />是否可見
<input id="chk2" type="checkbox" checked="checked" />是否可見
像checkbox,radio和select這樣的元素,選中屬性對應“checked”和“selected”,這些也屬於固有屬性,因此需要使用prop方法去操作才能獲得正確的結果。
$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true
如果上面使用attr方法,則會出現:
$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"