使用zTree实现树形下拉框

这两天项目中需要用到选择属性下拉框,树状结构我用了zTree,下拉框本想用插件的,但是没找到好的插件就只能自己搞出来了,正好网上也有一些zTree下拉框的例子,就做出来了

HTML:


js代码:

function zTreeBeforeClick(treeId, treeNode, clickFlag) {
			var check = (treeNode && !treeNode.isParent);
			if (!check){
				//alert("只能选择子节点...");
				var catObj = $("#catName");
				catObj.attr("value", "");
			}
			return check;
		}

		function zTreeOnClick(event, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("cateTree"), nodes = zTree
					.getSelectedNodes(), v = "", ids = "";
			nodes.sort(function compare(a, b) {
				return a.id - b.id;
			});
			v =  nodes[0].catName;
			ids = nodes[0].catId;
			//if (v.length > 0)
			//	v = v.substring(0, v.length - 1);
			var catObj = $("#catName"),catId = $("#catId");
			catObj.attr("value", v);
			catId.attr("value", ids);
		}

		function showMenu() {
			var cityObj = $("#catName");
			var cityOffset = $("#catName").offset();
			$("#menuContent").css({
				left : cityOffset.left + "px",
				top : cityOffset.top + cityObj.outerHeight() + "px"
			}).slideDown("fast");

			$("body").bind("mousedown", onBodyDown);
		}
		function hideMenu() {
			$("#menuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown);
		}
		function onBodyDown(event) {
			if (!(event.target.id == "menuBtn"
					|| event.target.id == "menuContent" || $(event.target)
					.parents("#menuContent").length > 0)) {
				hideMenu();
			}
		}
		var setting = {
				view: {
					selectedMulti: false
				},
				data : {
					key : {
						name : "catName"
					},
					simpleData : {
						enable : true,
						idKey : "catId",
						pIdKey : "parentId",
						rootPId : 0
					}
				},
				callback: {
					//beforeClick: zTreeBeforeClick,
	                onClick: zTreeOnClick
	            }
			};
		$(function() {
			$.getJSON('${cssRoot}/category/queryTree.do', {}, function(res) {
				$.fn.zTree.init($("#cateTree"), setting, res.list);
			});
		});

这次熟悉了zTree的一些api,包括callback、不需要多选的时候selectedMulti: false等等
 

 

 

 

你可能感兴趣的:(jquery)