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>

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

                                                                                                  快乐学习,快乐编程!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值