好久没用jQuery了,很多基础的东西都忘了,项目需要如下功能,自己整理了一套,拿来即用;
<!DOCTYPE html>
<html>
<head>
<title>jQuery实现全选,反选和选择动态生成的标签样例</title>
</head>
<script src="G:\\jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
//jquery无法获取动态生成的html标签,只能获取它的父标签-----jQuery on()
//https://www.cnblogs.com/zhangruiqi/p/7886442.html
$("body").on("click", ":checkbox[name=tab_order_id]", function() {
$("#head_checkbox").prop('checked', $(":checkbox[name=tab_order_id]").length == $(":checkbox[name=tab_order_id]:checked").length)
})
})
//全选
function checkAll() {
if ($("#head_checkbox").prop("checked")) {
$(":checkbox[name=tab_order_id]").each(function() {
$(this).prop('checked', true);
});
} else {
$("input[name=tab_order_id]").each(function() {
$(this).prop('checked', false);
});
}
}
//反选 <input type="checkbox" name="tab_order_id" value="001" onclick="reverseCheck()">
function reverseCheck() {
$("#head_checkbox").prop('checked', $(":checkbox[name=tab_order_id]").length == $(":checkbox[name=tab_order_id]:checked").length)
}
</script>
<body>
<!-- 静态的 -->
<input type="checkbox" id="head_checkbox" onclick="checkAll()">
<!-- 以下是模拟后台返回动态生成的标签 -->
<input type="checkbox" name="tab_order_id" value="001">
<input type="checkbox" name="tab_order_id" value="002">
<input type="checkbox" name="tab_order_id" value="003">
</body>
</html>