<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"