问题描述:模仿实现了网页上的全选按钮的功能.
代码比较简单,不多说了,直接上代码
<!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>
如果哪有不会的,留言就可以了。
快乐学习,快乐编程!