树状复选框

一、实现的具体功能

  

  

二、直接上代码

   

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>複選框</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<style>
.layer_Name{
margin-left: 16px;
}
</style>
</head>

<body>
<div class="layer_Type">
<img class="tree-img" src="./arrows.jpg" style="width: 13px;"/>
<input type="checkbox" class="parent_checkbox" οnclick="checkchange(this);" />
<label for="parent">父</label>
</div>
<div class="layer_Name">
<div>
   <input type="checkbox" class="child_checkbox" οnclick="checkchange(this);" />
   <label for="child">子</label>
</div>
<div>
   <input type="checkbox" class="child_checkbox" οnclick="checkchange(this);" />
   <label for="child">子</label>
</div>
</div>
<div class="layer_Type">
<img class="tree-img" src="./arrows.jpg" style="width: 13px;"/>
<input type="checkbox" class="parent_checkbox" οnclick="checkchange(this);" />
<label for="parent">父</label>
</div>
<div class="layer_Name">
<div>
   <input type="checkbox" class="child_checkbox" οnclick="checkchange(this);" />
   <label for="child">子</label>
</div>
<div>
   <input type="checkbox" class="child_checkbox" οnclick="checkchange(this);" />
   <label for="child">子</label>
</div>
</div>
</body>
<script>
$(".tree-img").click(function () {
// 获取需要隐藏或显示的节点
var $toggle_node = $(this).parent().next();
$toggle_node.slideToggle(); // 切换隐藏或显示
});
// 为所有的父节点添加点击事件
$(".parent_checkbox").click(function () {
// 获取父节点是否选中
var isChange = $(this).prop("checked");
if (isChange) {
// 如果选中,则父节点下的所有的子节点都选中
$(this).parent().next().find(".child_checkbox").prop("checked", true);
} else {
// 未选中,取消全选
$(this).parent().next().find(".child_checkbox").removeAttr("checked");
}
});
// 为所有的子节点添加点击事件
$(".child_checkbox").click(function () {
// 获取选中的节点的父节点下的所有子节点选中的数量
var length = $(this).parent().parent().find(".child_checkbox:checked").length;
// 判断当前结点是否选中
if ($(this).prop("checked")) {
// 如果当前节点选中后,所有的选中节点数量1,选中父节点
if (length == 1) {
// 选中父节点
$(this).parent().parent().prev().find(".parent_checkbox").prop("checked", true);
}
} else {
// 节点未选中
if (length == 0) {
// 取消父节点的选中状态
$(this).parent().parent().prev().find(".parent_checkbox").removeAttr("checked");
}
}
});
</script>

</html>

猜你喜欢

转载自www.cnblogs.com/luzaijiaoxia/p/11399001.html
今日推荐