1. 程式人生 > >分別用js和jQuery是實現表格的全選中和全不選

分別用js和jQuery是實現表格的全選中和全不選

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用jQuery和js完成複選框的全選和全不選</title>
<script type="text/javascript"
	src="../../resource/jquery/jquery-1.8.3.js"></script>
<!-- 		<script type="text/javascript" src="../../resource/jquery/jquery-1.11.0.js" ></script> -->
<script>

	//方法一:用js實現表格的全選中和全不選
	function selectAll() {
		var inputNodes = document.getElementsByClassName("selectOne");
		var stateNode = document.getElementById("select");

		for (var i = 0; i < inputNodes.length; i++) {
			inputNodes[i].checked = stateNode.checked;
		}
	}

	//方法二:用jQuery實現表格的全選中和全不選
	$(function() {
		$("#select").click(function() {
			//獲取下面所有的 複選框並將其選中狀態設定跟編碼的前端 複選框保持一致。
			//$("tbody input").attr("checked",this.checked);
			$("tbody input").prop("checked", this.checked);
		});
	});
</script>

</head>
<body>
	<table border="1" width="500" height="50" align="center" id="tbl">
		<thead>
			<tr>
				<td colspan="4"><input type="button" value="新增" /> <input
					type="button" value="刪除" /></td>
			</tr>
			<tr>
				<th><input type="checkbox" id="select" onclick="selectAll()"></th>
				<th>編號</th>
				<th>姓名</th>
				<th>年齡</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>1</td>
				<td>張三</td>
				<td>22</td>
			</tr>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>2</td>
				<td>李四</td>
				<td>25</td>
			</tr>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>3</td>
				<td>王五</td>
				<td>27</td>
			</tr>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>4</td>
				<td>趙六</td>
				<td>29</td>
			</tr>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>5</td>
				<td>田七</td>
				<td>30</td>
			</tr>
			<tr>
				<td><input type="checkbox" class="selectOne" /></td>
				<td>6</td>
				<td>汾九</td>
				<td>20</td>
			</tr>
		</tbody>
	</table>
</body>
</html>
哦了~