bootstrap-treeview插件使用

bootstrap-treeview是一款树形结构插件,可以根据项目需求来定制相应的树形菜单,使用bootstrap-treeview时需要用到的插件文件如下:


在html页面直接引用插件文件就可以使用了:

<script type="text/javascript"
	src="/lib/jquery/jquery-tree/bootstrap-treeview.min.js"></script>
首先在html页面给treeview一个初始化容器,如下:

<div class="treeview-h">
		   	 	<div id="treeview"></div>
		   	 </div>
		   	 <input type="hidden" id="treeId"/>
js代码如下:

//初始化树形结构数据
function initTreeData(stationId){
	$.ajax({
        type: 'POST',
        url: '/EquSetting/queryTreeViewByStationId',
        async:false,
        data:{"stationId":stationId},
        success: function(result) {
       	 if(result != null && result.length != 0){
       		showTree(result);
       	 }else{
            return;
         }
        },
        error: function(a) {
        },
        dataType: 'json'
    });
}
//初始化树形图
function showTree(data){
	Substation.DOMOperator.treeGenerate(data,$("#treeview"));

	$("#treeview").on('nodeSelected',function(event,node){
		var stationId = $("#Station").val();
		initYOYData(stationId,node.id);
		$("#treeId").val(node.id);
	});

	var searchNodes = $("#treeview").treeview('search',[data.equ_name,{
		ignoreCase:true,
		exactMatch:true,
		revelResults:false
	}]);
	
	if(searchNodes.length==1){
		var nodeId = searchNodes[0].nodeId;
		$("#treeview").treeview('selectNode',[nodeId,{silent:true}]);
	}else if(searchNodes.length>1){
		$.each(searchNodes, function(index, val) {
			
			var id = val.id;
			if(id==data.id){
				var nodeId = val.nodeId;
				$("#treeview").treeview('selectNode',[nodeId,{silent:true}]);
				return false;
			}					

		});
	}else{
		$("#treeview").treeview('selectNode',[0,{silent:true}]);
	}
}
//得到所有选中的节点id
function getTreeId(){
	var checkNode=$('#treeview').treeview('getSelected');
	$("#treeId").val(checkNode[0].id);
}

其中初始化treeview插件的方法我封装在了一个工具类中,如下:

		treeGenerate:function(data,$Tree,initObj){
			var treedata = new Array();
			var pattern = new RegExp('\\,\\"nodes\\"\\:\\[\\]','g');

			for(var i=0;i<data.length;i++){
				if(i==0){
					var state = {
						expanded:true
					};
					data[i].state=state;
				}
				var tempStr = JSON.stringify(data[i]);
				treedata.push(JSON.parse(tempStr.replace(pattern,"")));
			}
			if(initObj != null || initObj != undefined){
				initObj.levels=1;
				initObj.data = treedata;
				$Tree.treeview(initObj);
			}else{
				$Tree.treeview({
					data:treedata,
					showIcon:true,
					showCheckbox:false,
					showBorder:true,
					levels:1,
					multiSelect:false,
					highlightSearchResults:true,
					highlightSelected:true
				});
			}
			return this;
		},
		checkTreeChildNode:function(node,$Tree){
			var str = JSON.stringify(node);
			var pattern = new RegExp('nodes');
			if(pattern.test(str)){
				$.each(node.nodes, function(key, val) {
					$Tree.treeview('checkNode',[val.nodeId]);
					Substation.DOMOperator.checkTreeChildNode(val,$Tree);
				});
			}
		},
		unCheckTreeChildNode:function(node,$Tree){
			var str = JSON.stringify(node);
			var pattern = new RegExp('nodes');
			if(pattern.test(str)){
				$.each(node.nodes, function(key, val) {
					$Tree.treeview('uncheckNode',[val.nodeId]);
					Substation.DOMOperator.unCheckTreeChildNode(val,$Tree);
				});
			}
		},

因为treeview接收数据需要特定的数据格式,所以我们在查询到后台数据后进行简单的转化,如下:

public String queryTreeViewByStationId(Integer stationId) {
		try {
			List<Map<String, Object>> mList = equSettingMapper.queryTreeViewByStationId(stationId);
			List<Map<String, Object>> resultList = treeViewDataTransform(mList);
			ObjectMapper om = new ObjectMapper();
			String result = om.writeValueAsString(resultList);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	//树形结构数据转化
	public List<Map<String, Object>> treeViewDataTransform(List<Map<String, Object>> dataList){
		
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		String rootNodeId = new String();
		for(int i=0;i<dataList.size();i++){
			if(dataList.get(i).get("parent_id").toString().equals("p0")){
				rootNodeId=dataList.get(i).get("id").toString();
			}
		}
		for(int n=0;n<dataList.size();n++){
			Map<String,Object> temp = new HashMap<String,Object>();
			if(dataList.get(n).get("parent_id").toString().equals(rootNodeId)){
				temp.put("text", dataList.get(n).get("layer_name").toString());
				temp.put("id", dataList.get(n).get("EquIndex").toString());
				List<Map<String, Object>> bList = new ArrayList<Map<String,Object>>();
				for(int m=0;m<dataList.size();m++){
					Map<String,Object> bTemp = new HashMap<String,Object>();
					if(dataList.get(m).get("parent_id").toString().equals(dataList.get(n).get("id").toString())){
						bTemp.put("text", dataList.get(m).get("layer_name").toString());
						bTemp.put("id", dataList.get(m).get("EquIndex").toString());
						List<Map<String, Object>> cList = new ArrayList<Map<String,Object>>();
						for(int t=0;t<dataList.size();t++){
							Map<String,Object> cTemp = new HashMap<String,Object>();
							if(dataList.get(t).get("parent_id").toString().equals(dataList.get(m).get("id").toString())){
								cTemp.put("text", dataList.get(t).get("layer_name").toString());
								cTemp.put("id", dataList.get(t).get("EquIndex").toString());
							}
							if(!cTemp.isEmpty()){
								cList.add(cTemp);
							}
						}
						if(!cList.isEmpty()){
							bTemp.put("nodes", cList);
						}
					}
					if(!bTemp.isEmpty()){
						bList.add(bTemp);
					}
				}
				if(!bList.isEmpty()){
					temp.put("nodes", bList);
				}
			}
			if(!temp.isEmpty()){
				resultList.add(temp);
			}
			
		}
		return resultList;
	}
效果如图:

还有另一种使用方法,在控件上显示多选框,同时控制树形结构的级联选择:

html如下:

<div class="cascade">
						<p>
							<span>支路选择:</span><input id="multiState" type="checkbox"/>
							级联选择
						</p>
					</div>
					<div class="treeview-h energy-h">
						<div id="treeview"></div>
					</div>
js如下:

//初始化树形结构数据
function initTreeData(stationId){
	$.ajax({
        type: 'POST',
        url: '/EquSetting/queryTreeViewByStationId',
        async:false,
        data:{"stationId":stationId},
        success: function(result) {
       	 if(result != null && result.length != 0){
       		showTree(result);
       	 }else{
            return;
         }
        },
        error: function(a) {
        },
        dataType: 'json'
    });
}
//得到所有选中的节点id
function getTreeId(){
	var checkNodesArray=$('#treeview').treeview('getChecked');
	var checkNodeId = [];
	$.each(checkNodesArray,function(index,value) {
		checkNodeId.push(value.id);
	})
	$("#treeId").val(checkNodeId.join('-'));
}
//初始化树形结构
var nodesArray=[];
function showTree(data){
	var initTree = {
		showIcon:false,
		showCheckbox:true,
		showBorder:true,
		levels:2,
		highlightSearchResults:false,
		highlightSelected:false
	};
	Substation.DOMOperator.treeGenerate(data,$("#treeview"),initTree);

	//级联选择:选中
	$("#treeview").on('nodeChecked',function(event,node){

		if($("#multiState").prop('checked'))
			checkChildren(node,$('#treeview'));
		else
			$("#treeview").treeview('checkNode',[node.nodeId,{silent:true}]);
	});
	//级联选择:取消选中
	$("#treeview").on('nodeUnchecked',function(event,node){
		if($("#multiState").prop('checked'))
			unCheckChildren(node,$("#treeview"));
		else
			$("#treeview").treeview('uncheckNode',[node.nodeId,{silent:true}]);
	});
	//初始化成功默认选中所有节点
	$("#treeview").treeview('checkAll');
}

function checkChildren(node,$Tree){
	var str = JSON.stringify(node);
	var pattern = new RegExp('nodes');
	if(pattern.test(str)){
		$.each(node.nodes, function(key, val) {
			console.log(val.id);
			$Tree.treeview('checkNode',[val.nodeId]);
			checkChildren(val,$Tree);
		});
	}
}

function unCheckChildren(node,$Tree){
	var str = JSON.stringify(node);
	var pattern = new RegExp('nodes');
	if(pattern.test(str)){
		$.each(node.nodes, function(key, val) {
			$Tree.treeview('uncheckNode',[val.nodeId]);
			unCheckChildren(val,$Tree);
		});
	}
}
效果图:







已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页