Jquery实现checkbox name是数组的情况下的全选/反选的2种写法

来源:互联网 发布:图片标注软件 编辑:程序博客网 时间:2024/06/10 07:43

示例代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Example</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</HEAD>
<BODY>
方法1:<br>
<input type="checkbox" id="rankclick">全选/反选<br>
<input type="checkbox" name="rank[]" value="100">100<br>
<input type="checkbox" name="rank[]" value="200">200<br>
<input type="checkbox" name="rank[]" value="300">300<br>
============================================================
<br>
方法2:<br>
<input type="checkbox" id="productclick">全选/反选<br>
<input type="checkbox" name="product[]" value="001" id="check">001<br>
<input type="checkbox" name="product[]" value="002" id="check">002<br>
<input type="checkbox" name="product[]" value="003" id="check">003
<script type="text/javascript">

/* 方法1 */
$('#rankclick').click(function(){
 $("input[name='rank[]']").each(function(e){
 $(this).attr("checked",$('#rankclick').attr("checked"));
 });
});

/* 方法2 */
$('#productclick').click(function(){
 $('[id=check]:checkbox').each(function(e){
 $(this).attr("checked",$('#productclick').attr("checked"));
 });
});
</script>
</BODY>
</HTML>

第1种写法更简洁和标准,第2种写法是把每个checkbox加个相同的id,同样能实现功能,但这可能不太符合常规。