本文实例为大家讲解了jquery zTree树插件的基本使用方法,具体内容如下
一、节点模糊搜索功能:搜索成功后,自动高亮显示并定位、展开搜索到的节点。
二、节点异步加载:1、点击展开时加载数据;2、选中节点时加载数据。 前台代码如下:
var checkFlag = true; //是否选中
//节点展开前
function zTreeBeforeExpand(treeId,treeNode) {
reloadFlag = false;
return true;
};
//节点创建后
function zTreeOnNodeCreated(event,treeId,treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
if (reloadFlag) {
if (checkFlag) {
zTree.checkNode(treeNode,true,true);
}
if (!treeNode.children) {
zTree.reAsyncChildNodes(treeNode,"refresh");
}
}
};
//选中节点前
function zTreeBeforeCheck(treeId,treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
if (!treeNode.children) {
reloadFlag = true;
checkFlag = true;
zTree.reAsyncChildNodes(treeNode,"refresh");
}
return true;
}
//页面加载完成
_run(function () {
require(['zTree/js/jquery.ztree.all-3.5'],function () {
$.ajax({
type: "POST",success: function (data) {
if (data && data.length != 0) { //如果结果不为空
$.fn.zTree.init($("#tree"),setting,data);
}
else { //搜索不到结果
}
}
});
});
//提交
$("#inputSubmit").click(function () {
var zTree = $.fn.zTree.getZTreeObj("tree");
var nodes = zTree.getCheckedNodes(true);
var ids = "";
var names = "";
for (var i = 0; i < nodes.length; i++) { //遍历选择的节点集合
if (!nodes[i].isParent) {
ids += nodes[i].id.replace("level" + nodes[i].level,"") + ",";
names += nodes[i].name + ",";
}
}
Simpo.ui.Box.hideBox();
parent.$(".BoxFrm").contents().find("#inputRange").val(names.substr(0,names.length - 1));
parent.$(".BoxFrm").contents().find("#hidRange").val(ids.substr(0,ids.length - 1));
})
});
//查找节点
var lastNodeList = [];
var lastKey;
function searchNode() {
var zTree = $.fn.zTree.getZTreeObj("tree");
var key = $.trim($("#inputSearchNode").val());
if (key != "" && key != lastKey) {
nodeList = zTree.getNodesByParamFuzzy("name",key);
for (var i = 0,l = lastNodeList.length; i < l; i++) { //上次查询的节点集合取消高亮
lastNodeList[i].highlight = false;
zTree.updateNode(lastNodeList[i]);
}
zTree.expandAll(false); //全部收缩
if (nodeList.length > 0) {
for (var i = 0,l = nodeList.length; i < l; i++) { //遍历找到的节点集合
if (nodeList[i].getParentNode()) {
zTree.expandNode(nodeList[i].getParentNode(),false,false); //展开其父节点
}
nodeList[i].highlight = true;
zTree.updateNode(nodeList[i]);
}
}
zTree.refresh(); // 很重要,否则节点状态更新混乱。
lastNodeList = nodeList;
lastKey = key;
}
}
//加载数据
function loadData() {
var zTree = $.fn.zTree.getZTreeObj("tree");
var rootNodes = zTree.getNodes();
reloadFlag = true;
checkFlag = false;
for (var i = 0; i < rootNodes.length; i++) {
if (!rootNodes[i].children) {
zTree.reAsyncChildNodes(rootNodes[i],"refresh"); //异步加载
}
}
}
//全部收缩
function closeAll() {
var zTree = $.fn.zTree.getZTreeObj("tree");
if ($("#inputCloseAll").val() == "全部收缩") {
zTree.expandAll(false);
$("#inputCloseAll").val("全部展开")
}
else {
zTree.expandAll(true);
$("#inputCloseAll").val("全部收缩")
}
}
//高亮样式
function getFontCss(treeId,treeNode) {
return (treeNode.highlight) ? { color: "#A60000","font-weight": "bold"} : { color: "#333","font-weight": "normal" };
}