欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

下拉树,,纠结了很久,终于搞定。下

来源: javaer 分享于  点击 32445 次 点评:242

下拉树,,纠结了很久,终于搞定。下


纠结了很久,终于搞定。下面分享下:

common.js

var $iDiv ;function Offset(e) {     var t = e.offsetTop;     var l = e.offsetLeft;     var w = e.offsetWidth-2;     var h = e.offsetHeight-2;     while(e=e.offsetParent)     {         t+=e.offsetTop;         l+=e.offsetLeft;     }     return {         top : t,         left : l,         width : w,         height : h     };} function initSelect(obj,url,dept_name){    var $Obj = $("#"+obj);    var $Obj_name = $("#"+obj+"_name");    var offset_text=Offset($Obj.get(0));    $Obj.css("display","none");    $iDiv = $("<div id='selectof"+obj+"'></div>");    $iDiv.css("width",offset_text.width+"px");    $iDiv.css("height",offset_text.height+"px");    $iDiv.css("z-index","2");    $iDiv.css("background","url(images/icon_select.gif) no-repeat right 4px");    $iDiv.css("border","1px solid #7C9BCF");    $iDiv.css("fontSize","12px");    $iDiv.css("lineHeight",offset_text.height+"px");    $iDiv.css("textIndent","4px");    if($Obj_name.val()==""||$Obj_name.val()==null){        $iDiv.text("��ѡ��");    }else{        $iDiv.text($("#"+obj+"_name").val());    }    $Obj.parent().append($iDiv);    $iDiv.click(function(){        if($("#selectchild"+obj).length==1){            if(($("#selectchild"+obj+":hidden").length==1)){                var offset_div = Offset($iDiv.get(0));                $("#selectchild"+obj).css("top",offset_div.top+offset_div.height+2+"px");                $("#selectchild"+obj).css("left",offset_div.left+"px");                $("#selectchild"+obj).css("display","block");            }else{                $("#selectchild"+obj).css("display","none");            }        }else{            var $cDiv = $("<div id='selectchild"+obj+"'></div>");            $cDiv.css("position","absolute");            $cDiv.css("top",offset_text.top+offset_text.height+2+"px");            $cDiv.css("left",offset_text.left+"px");            $cDiv.css("width",offset_text.width+"px");            $cDiv.css("z-index","3");            $cDiv.css("background","#f7f7f7");            $cDiv.css("border","1px solid silver");            $deptDiv = $("<div></div>");            conf={data:{                type:"json",                            url:url                },                ui : {                    theme_name : "classic"                },                callback:{                     onselect   : function(node) {                        if(node.getAttribute("selectable")!="false"){                            if(dept_name != undefined )$("#"+dept_name).val($(node).children().eq(0).text());                            $iDiv.text($(node).children().eq(0).text());                            $Obj_name.val($(node).children().eq(0).text());                            $("#"+obj).val(node.id);                            $("#"+obj).change();                            $cDiv.css("display","none");                        }                                       }                }                       };            deptTree.init($deptDiv, $.extend({},conf));            $cDiv.append($deptDiv);            $("body").append($cDiv);        }    });}function setText(text){    $iDiv.text(text);}

tree_component.css

/* TREE LAYOUT */.tree ul { margin:0 0 0 5px; padding:0 0 0 0; list-style-type:none; }.tree li { display:block; min-height:18px; line-height:18px; padding:0 0 0 14px; margin:0 0 0 0; /* Background fix */ clear:both; _height:18px; #height:auto; }.tree li ul { display:none; }.tree li a, .tree li span { display:inline-block;line-height:16px;height:16px;color:black;white-space:nowrap;text-decoration:none;padding:1px 4px 1px 1px;margin:0; }.tree li a:focus { outline: none; }.tree li a input, .tree li span input { margin:0;padding:0 0;display:inline-block;height:12px !important;border:1px solid white;background:white;font-size:10px;font-family:Verdana; }.tree li a input:not([class="xxx"]), .tree li span input:not([class="xxx"]) { padding:1px 0; }/* FOR DOTS */.tree .ltr li.last { float:left; }.tree .rtl li.last { float:right; #float:none; _float:right; }.tree > ul li.last { overflow:visible; }/* OPEN OR CLOSE */.tree li.open ul { display:block; }.tree li.closed ul { display:none !important; }/* FOR DRAGGING */#jstree-dragged { position:absolute; top:-10px; left:-10px; margin:0; padding:0; }#jstree-dragged .rtl { _width:20px; #width:200px; margin:0; padding:0;} #jstree-dragged ul ul ul { display:none; }/* RTL modification */.tree .rtl, .tree .rtl ul { margin:0 5px 0 0; }.tree .rtl li { padding:0 14px 0 0; }.tree .rtl li a, .tree .rtl li span { padding:1px 1px 1px 4px; }/* CONTEXT MENU */.tree-context { display:none; position:absolute; list-style-type:none; margin:0; padding:0; left:-2000px; top:-2000px; }.tree-context .separator { display:none; }.tree-context a { display:block; margin:0; padding:0; }/** FIREFOX2 fix **/.tree .ltr li a, x:-moz-any-link { display:inline; float:left; }.tree .rtl li a, x:-moz-any-link { display:inline; float:right; }.tree li ul, x:-moz-any-link { clear:both; }/** FIREFOX3 restore **/.tree .ltr li a, .tree .rtl li a, x:-moz-any-link, x:default { display:inline-block; float:none; }.tree li ul, x:-moz-any-link, x:default { clear:none; }/** IE7 Restore **/.tree .ltr li a, .tree .rtl li a { #display:inline-block; #float:none; }.tree li ul { #clear:none; }.tree li { _width:1px; }.tree li li { overflow:hidden; #overflow:visible; _overflow:visible; }.tree > .ltr > li { display:table; }.tree > .rtl > li { display:table; }/* EXPLORER 6 and 7 fix for 2px whitespace */.tree .ltr li.last { #margin-top: expression( (this.previousSibling && /open/.test(this.previousSibling.className) ) ? "-2px" : "0"); _margin-top: expression( (this.previousSibling && /open/.test(this.previousSibling.className) ) ? "-2px" : "0"); }.tree .rtl li.last { _margin-top: expression( (this.previousSibling && /open/.test(this.previousSibling.className) ) ? "-2px" : "0"); }/* OPERA SCROLLBAR ISSUE */@media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0) {    head~body .tree > ul > li.last > ul { margin-bottom:36px; }    .tree li li { overflow:visible; }}/*FIREFOX FIX@-moz-document url-prefix() {} */

css.js

function get_css(rule_name, stylesheet, delete_flag) {    if (!document.styleSheets) return false;    rule_name = rule_name.toLowerCase(); stylesheet = stylesheet || 0;    for (var i = stylesheet; i < document.styleSheets.length; i++) {         var styleSheet = document.styleSheets[i]; css_rules = document.styleSheets[i].cssRules || document.styleSheets[i].rules;        if(!css_rules) continue;        var j = 0;        do {            //if(i == 2 && j > 30) alert(css_rules[j].selectorText.toLowerCase() + " " + rule_name);            if(css_rules.length && j > css_rules.length + 5) return false;            if(css_rules[j].selectorText && css_rules[j].selectorText.toLowerCase() == rule_name) {                if(delete_flag == true) {                    if(document.styleSheets[i].removeRule) document.styleSheets[i].removeRule(j);                    if(document.styleSheets[i].deleteRule) document.styleSheets[i].deleteRule(j);                    return true;                }                else return css_rules[j];            }        }        while (css_rules[++j]);    }    return false;}function add_css(rule_name, stylesheet) {    rule_name = rule_name.toLowerCase(); stylesheet = stylesheet || 0;    if (!document.styleSheets || get_css(rule_name, stylesheet)) return false;    (document.styleSheets[stylesheet].insertRule) ? document.styleSheets[stylesheet].insertRule(rule_name+' { }', 0) : document.styleSheets[stylesheet].addRule(rule_name, null, 0);    return get_css(rule_name, stylesheet);}function get_sheet_num (href_name) {    if (!document.styleSheets) return false;    for (var i = 0; i < document.styleSheets.length; i++) { if(document.styleSheets[i].href && document.styleSheets[i].href.toString().match(href_name)) return i; }     return false;}function remove_css(rule_name, stylesheet) { return get_css(rule_name, stylesheet, true); }function add_sheet(url, media) {    if(document.createStyleSheet) {        document.createStyleSheet(url);    }    else {        var newSS   = document.createElement('link');        newSS.rel   = 'stylesheet';        newSS.type  = 'text/css';        newSS.media = media || "all";        newSS.href  = url;        // var styles   = "@import url(' " + url + " ');";        // newSS.href   ='data:text/css,'+escape(styles);        document.getElementsByTagName("head")[0].appendChild(newSS);    }}

[Java]代码

<script type="text/javascript" src="<%=path%>/calllist/js/jstree/css.js"></script><script src="<%=path%>/calllist/js/jstree/tree_component.js" type="text/javascript"></script><script src="<%=path%>/calllist/js/common.js" type="text/javascript"></script><link rel="stylesheet" type="text/css" href="<%=path%>/calllist/js/jstree/tree_component.css" /><script type="text/javascript">     $(document).ready(function() {        initSelect("DEPT_ID", "../servlet/deptTreeServlet","DEPT_NAME");//调用方法需要两个参数1 被模拟的text文本框ID 2 提供jsTree 所需json数据的后台</script><body><table><tr><td><td  align="right" >责任部门:</td>                <td  align="left" colspan="3">                <input style="width: 450px;" type="text" id="DEPT_ID" name="DEPT_ID" value="" />                 <input type="hidden"  id="DEPT_NAME" name="DEPT_NAME" value="" />                </td></td></tr></table></body>

DeptTreeServlet.java

package com.eshore.ccc.servlet;import java.io.IOException;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import org.apache.commons.lang.xwork.StringUtils;import org.springframework.web.context.ContextLoader;import org.springframework.web.context.WebApplicationContext;import com.eshore.ccc.bean.DeptBean;import com.eshore.ccc.dao.imp.DeptDao;import com.eshore.ccp.structure.EnterPriserModel;import com.eshore.ccp.structure.FrameUserModel;import com.eshore.ccp.structure.exception.EntityNotFoundException;public class DeptTreeServlet extends HttpServlet {    /**     *      */    private static final long serialVersionUID = 5671012385600445547L;    @Override    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        //System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation());        System.out.println("===================================================");        WebApplicationContext context= ContextLoader.getCurrentWebApplicationContext();         DeptDao deptDao =  (DeptDao) context.getBean("deptDao");         String userCode = request.getRemoteUser();         String ent_code = "";         try {            FrameUserModel model = new FrameUserModel(userCode);            ent_code = model.getEntCode();        } catch (EntityNotFoundException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        }        List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();        try {            EnterPriserModel emp = new EnterPriserModel(ent_code);            List<DeptBean> deptList = deptDao.getDeptBeanByEntCode(ent_code);            Map<String, Object> mapNode = new LinkedHashMap<String, Object>();            Map<String, Object> mapAttr = new LinkedHashMap<String, Object>();            Map<String, Object> mapData = new LinkedHashMap<String, Object>();            List<Map<String, Object>> subNodes = getSubNodes(ent_code , ent_code, deptList);            mapAttr.put("id", ent_code);            mapData.put("title", emp.getEntCnName());//            mapNode.put("attributes", mapAttr);//            mapNode.put("state", "open");            mapNode.put("data", mapData);            mapNode.put("children", subNodes);//            root.add(mapNode);        } catch (EntityNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        JSONArray jsonArray = JSONArray.fromObject(root);        System.out.println(jsonArray.toString());        renderJson(response, jsonArray.toString());    }    @Override    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }    private List<Map<String, Object>> getSubNodes(String id,String ent_code,            List<DeptBean> departmentList) {        // TODO Auto-generated method stub        List<Map<String, Object>> subNodes = new ArrayList<Map<String, Object>>();        for (DeptBean dept : departmentList) {            if(dept.getPdept_code() == null){                dept.setPdept_code(ent_code);            }            if (dept.getPdept_code().equals(id)) {                Map<String, Object> mapNode = new LinkedHashMap<String, Object>();                Map<String, Object> mapAttr = new LinkedHashMap<String, Object>();                Map<String, Object> mapData = new LinkedHashMap<String, Object>();                mapAttr.put("id", dept.getDept_code());                mapData.put("title", dept.getDept_name());                mapNode.put("attributes", mapAttr);                if (dept.getSub_counts().toString().equals("0"))                    mapNode.put("state", "file");                else                    mapNode.put("state", "open");                mapNode.put("data", mapData);                mapNode.put("children", getSubNodes(dept.getDept_code(),ent_code,                        departmentList));                subNodes.add(mapNode);            }        }        return subNodes;    }    public static void renderJson(HttpServletResponse response, String string,            String... headers) {        render(response, "application/json", string, headers);    }    public static void render(HttpServletResponse response, String contentType,            String content, String... headers) {        try {            String encoding = "GBK";            boolean noCache = true;            for (String header : headers) {                String headerName = StringUtils.substringBefore(header, ":");                String headerValue = StringUtils.substringAfter(header, ":");                if (StringUtils.equalsIgnoreCase(headerName, "GBK")) {                    encoding = headerValue;                } else if (StringUtils.equalsIgnoreCase(headerName, "true")) {                    noCache = Boolean.parseBoolean(headerValue);                } else                    throw new IllegalArgumentException(headerName + "����");            }            String fullContentType = contentType + ";charset=" + encoding;            response.setContentType(fullContentType);            if (noCache) {                response.setHeader("Pragma", "No-cache");                response.setHeader("Cache-Control", "no-cache");                response.setDateHeader("Expires", 0);            }            response.getWriter().write(content);        } catch (IOException e) {        }    }}
相关栏目:

用户点评