遇到要写checkbox全选的时候,每次都要到网上搜一遍,这次记录下来,一劳永逸,省得以后老是忘记!
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<style>
* {
margin: 0px;
padding: 0px;
}
body {
padding-left: 10px;
}
</style>
<body>
<input type="checkbox" onclick="checkAll(this);" id="check_all"/> 全选/全不选
<button onclick="add();">添加</button>
<button onclick="remove();">删除</button>
<ul>
</ul>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
function checkAll(source) {
var checked = $(source).is(":checked");
if (checked) {
$("ul").find("input[type=checkbox]").not(":checked").prop("checked", checked);
} else {
$("ul").find("input[type=checkbox]:checked").prop("checked", checked);
}
}
function check(source) {
if ($("#check_all").is(":checked") && !$(source).is(":checked")) {
$("#check_all").prop("checked", false);
}
}
function add() {
$("ul").append("<ol><input type='checkbox' onclick='check(this);'/> 选项--" + ($("ul").find("ol").length + 1) + "</ol>");
}
function remove() {
if (!$("ul").find("input[type=checkbox]:checked").length) {
alert("请选择要操作的选项");
return;
}
$("ul").find("input[type=checkbox]:checked").parent().remove();
$("#check_all").prop("checked", false);
}
</script>
</html>
在设置checkbox的选中/未选中有一个需要注意的问题就是要使用prop方法来实现,而不要使用attr,会有bug。
这样做的主要原因是对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
checkbox,radio和select,选中属性对应”checked”和”selected”,他们属于固有属性,应该使用prop方法去操作。
参考:http://www.cnblogs.com/tangge/p/5086235.html
参考:http://www.cnblogs.com/Showshare/p/different-between-attr-and-prop.html