bootstrap 里面没有自带的下拉树插件,所以用了bootstrap加上ztree下拉树的形式
但是这个过程代码量多,复杂,因为我的页面有多个下拉树,这样实现起来很不方便,所以在此写了一个jquery的扩展插件
/** * 公共的部门的下拉 */ ;(function($){ var me;//input输入框 var selectId=""; var treeId=""; $.fn.buildButtomTree=function(data,_id){ selectId=!!_id?_id:""; treeId="treeDemo"+(Math.random()*100).toFixed(0); if(_id){ this.val(depObj[_id]); this.attr("departmentval",depObj[_id]); } // var data=[ // {id: "101001", name: "计划财务部", pId: "001", code: "101001"}, // {id: "105001", name: "港吉", pId: "001", code: "105001"}, // {id: "001", name: "整个公司", pId: "000", code: "001"} // ] //构建html var str= '<div class="menuContent" style="display:none;overflow:auto; border: 1px solid #ddd; position: absolute;z-index: 999;background-color: #fff;">'+ '<ul id="'+treeId+'" class="ztree" style="margin-top:0;width:177px"></ul>'+ '</div>'; this.parent().append(str); this.click(function(){ me=$(this); showMenu(); }) initTreeData(data,this); } var initTreeData=function(zNodes,el){ me=el; var setting = { view: { selectedMulti: false //是否允许多选 }, data: { simpleData: { enable: true } }, callback: { //zTree节点的点击事件 onClick: function(e, treeId, treeNode){ var zTree = $.fn.zTree.getZTreeObj(treeId), nodes = zTree.getSelectedNodes(); var v = "",c=""; nodes.sort(function compare(a,b){return a.id-b.id;}); for (var i=0, l=nodes.length; i<l; i++) { v += nodes[i].name + ","; //v += nodes[i].name; //c += nodes[i].code + ","; c += nodes[i].code; } if (v.length > 0 ) v = v.substring(0, v.length-1); var cityObj =me; cityObj.val(v); cityObj.attr("departmentval", c); hideMenu(); } } }; //var $tree=el.next().find(".ztree"); $.fn.zTree.init($("#"+treeId), setting, zNodes); var zTree = $.fn.zTree.getZTreeObj(treeId); if(!!selectId){ var node=zTree.getNodeByParam("id",selectId); console.log(node); //设置选中 zTree.selectNode(node); } zTree.expandAll(true); } var hideMenu=function(){ me.next().fadeOut("fast"); $("body").unbind("mousedown", onBodyDown); } var onBodyDown=function(){ if (!(event.target.id == "menuBtn" || event.target.className == "menuContent" || $(event.target).parents(".menuContent").length>0)) { hideMenu(); } } var showMenu=function(){ me.next().slideDown("fast"); $("body").bind("mousedown", onBodyDown); } })(jQuery);
原理其实和ztree下拉树同样的原理,只不过是现在通用的