参考:https://blog.csdn.net/u011113654/article/details/49853271
一、实现的具体功能
1、最左边的图形按钮实现子目录的隐藏和显示
2、点击父节点的复选框,父节点下的所有的子节点都被选中;若父节点未选中,则下面的所有子节点取消选中(全选和全不选)
3、选中一个子节点时相应的父节点也被选中;当所有的子节点都没有选中时,父节点也取消选中。
二、JS代码
2.1 子目录的隐藏和显示
<div class="layer_Type">
<img class="tree_node_toggle_img" style="float:left;margin-top:8px;" src="${ctx}/gis/image/togger.png" />
<input type="checkbox" id="tdt" class="parent_checkbox" onclick="checkchange(this);"/>
<label for="tdt">天地图</label>
</div>
<div class="layer_Name">
<div>
<input type="checkbox" id="tdt_ditu" class="child_checkbox" onclick="checkchange(this);"/>
<label for="tdt_ditu">天地图底图</label>
</div>
<div>
<input type="checkbox" id="tdt_zhuji" class="child_checkbox" onclick="checkchange(this);"/>
<label for="tdt_zhuji">天地图地注记</label>
</div>
</div>
上面是某一小段树形结构的HTML结构;下面是子目录的隐藏和显示点击事件:
$(".tree_node_toggle_img").click(function () {
// 获取需要隐藏或显示的节点
var $toggle_node = $(this).parent().next();
$toggle_node.slideToggle(); // 切换隐藏或显示
});
2.2 全选/全不选
// 为所有的父节点添加点击事件
$(".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");
}
});
注:切换checkbox的选中要用prop()方法,不能用attr()。
关于prop和attr的区别可自行了解。
4.选中子节点后父节点的相应变化状态
// 为所有的子节点添加点击事件
$(".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");
}
}
});