jQuery實現全選按鈕

問題描述:模仿實現了網頁上的全選按鈕的功能.


代碼比較簡單,不多說了,直接上代碼

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>模擬實現全選按鈕</title>
 </head>
 <body>
	<button>添加</button><button>刪除</button>全選<input type="checkbox" id="seleAll"/>
	<table border="1px">
		<tr>
			<td>選擇</td>
			<td>姓名</td>
			<td>班級</td>
			<td>年齡</td>
		</tr>

		<tr>
			<td><input type="checkbox"/></td>
			<td>Tom</td>
			<td>One</td>
			<td>17</td>
		</tr>
		<tr>
			<td><input type="checkbox"/></td>
			<td>Json</td>
			<td>Two</td>
			<td>17</td>
		</tr>
		<tr>
			<td><input type="checkbox"/></td>
			<td>Mary</td>
			<td>Two</td>
			<td>17</td>
		</tr>
	</table>
 </body>
 <script src=" jquery-1.11.1.min.js "></script>
	<script>
		//添加按鈕的邏輯
		$("button:first").click(function(){
			var $tr = "";
			if($(":checkbox:first").prop("checked")){//如果全選按鈕選中了,則添加的行的第一列的複選框選中了
				$tr = "<tr><td><input type='checkbox' checked='checked'/></td><td>James</td><td>Three</td><td>18</td></tr>"
			}else{
				$tr = "<tr><td><input type='checkbox'/></td><td>James</td><td>Three</td><td>18</td></tr>"
			}
			
			$("table").append($tr);
		});
		//刪除按鈕的邏輯
		$("button:last").click(function(){
			$("input:checked:not(:first)").parent().parent().remove();
		});
		//全選按鈕的點擊事件
		$("#seleAll").click(function(){
			$(":checkbox:gt(0)").prop("checked",$(":checkbox:first").prop("checked"));
		});
		//對每一個複選框判斷是否選中
		$(document).on("click",":checkbox:gt(0)",function(){
			var num = 0;
			$(":checkbox:gt(0)").each(function(){
				
				var checked = $(this).prop("checked");
				if(!checked){
					$(":checkbox:first").prop("checked",false);
				}
				else{
					num++;
				}
				
			});
			
			if(num==$(":checkbox:gt(0)").size()){
				$(":checkbox:first").prop("checked",true);
			}
		});
	</script>
</html>

如果哪有不會的,留言就可以了。

                                                                                                  快樂學習,快樂編程!

發佈了20 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章