`
kanpiaoxue
  • 浏览: 1747842 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

jQuery 全选checkbox的实现

 
阅读更多

我自己写了一个例子,用jQuery全选checkbox。

附件中有完整的代码。

<html>
<head>
<style>
table {
	border: 1px solid black;
}

.checkbox {
}
</style>
<script type="text/javascript" src='jquery-1.10.2.js'></script>
<script type="text/javascript">
	$(function() {
		//给全选的checkbox添加动作
		$('#checkboxAllId').click(function() {
			if ($(this).prop('checked')) {
				$('.checkbox').each(function(i, d) {
					$(this).prop('checked', true);
				});
			} else {
				$('.checkbox').each(function(i, d) {
					$(this).prop('checked', false);
				});
			}
		});

		//给每一个子checkbox添加动作
		var checkboxObj = $('.checkbox');
		checkboxObj.click(function(i, d) {
			var checkedArr = [];
			var checkboxArr = [];
			if ($(this).prop('checked')) {
				checkboxObj.each(function(i, d) {
					if ($(this).prop('checked')) {
						checkedArr.push(this);
					}
					checkboxArr.push(this);
				});
				$('#checkboxAllId').prop('checked',
						(checkedArr.length == checkboxArr.length));

			} else {
				$('#checkboxAllId').prop('checked', false);
			}
		});

	});
</script>
</head>
<body>
	<table>
		<tr>
			<td><input type="checkbox" id="checkboxAllId" value="-1" />全选</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="1" />1</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="2" />2</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="3" />3</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="4" />4</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="5" />5</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="6" />6</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="7" />7</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="8" />8</td>
		</tr>
		<tr>
			<td><input type="checkbox" class="checkbox" value="9" />9</td>
		</tr>
	</table>
</body>
</html>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics