<!-- 引入zTree css及js资源 -->
<link href="zTree/zTreeStyle.css" type="text/css" rel="stylesheet">
<script src="zTree/jquery-2.1.4.min.js"></script>
<script src="zTree/jquery.ztree.all.min.js"></script>
<table class="table">
<tr>
<td>
<div>
<ul>
<li>
<span>
<i>
<a id="enda" href="#">测试文字</a>
</i>
</span>
</li>
</ul>
</div>
</td>
</tr>
</table>
<hr>
<!-- zTree容器 -->
<ul id="tree" class="ztree" style="width:500px; overflow:auto;"></ul>
<script>
$(function(){
// 返回jQuery对象所有匹配元素的标识信息数组,每个元素形如:tagName或tagName#id(如果有id的话)
function getTagsInfo($doms){
return $doms.map(function(){
return this.tagName + (this.id ? "#" + this.id : "");
}).get();
}
//获取tag的祖先元素
var $parents = $("#enda").parents();
//获取tag的祖先元素的标签名
var tagName = getTagsInfo($parents);
//console.log(typeof tagName); 返回obj
//将对象转换为字符串
var tagNameStr = tagName.toString();
//将标称名转换为小写
var tagNameStrLowerCase = tagNameStr.toLowerCase();
//返回一个只包含标签名的数组
var tags = tagNameStrLowerCase.split(",");
//console.log(tags);
var tagsReverse = tags.reverse()
//创建一个空数组
let arrList = [];
for (var i=0; i<tagsReverse.length; i++) {
var t = {};
t.name = tagsReverse[i];
t.open = true;
t.id = i+1;
t.parentid = i;
arrList.push(t); // 向arrList空数组中push新组织好的数据
}
//console.log(arrList);
//修改数组结构的方法
function changeArr(data, parentid) {
var result = [], temp;
for (var i = 0; i < data.length; i++) {
if (data[i].parentid== parentid) {
var obj = {"name": data[i].name,"open": true,"id": data[i].id};
temp = changeArr(data, data[i].id);
if (temp.length > 0) {
obj.children = temp;
}
result.push(obj);
}
}
return result;
}
var zTreeNodesNew = changeArr(arrList,0);
//console.log(zTreeNodesNew);
var setting={
check: {
enable: false,
chkStyle: "checkbox"//显示 checkbox 选择框,默认checkbox可选择值radio
}
};
var city = $.fn.zTree.init($("#tree"), setting, zTreeNodesNew);
//第一个参数为zTree的DOM容器,第二个为zTree设置详情可见官网api,第三个为zTree的节点数据
})
</script>
来源:CSDN
作者:RightHereWaitingFY
链接:https://blog.csdn.net/luyundesign/article/details/103781197