ztreeDeptSelect 基於jquery和ztree的部門選擇插件


插件介紹

首先我們來看插件的功能演示(效果):

插件准備好后。前台只需編寫html:

<input type="text" class="deptName" />

然后在javascript中渲染插件(代碼使用jQuery寫法):

$(".deptName").ztreeDeptSelect();

插件即渲染完成。

 

此插件已發布至github,源碼地址: https://github.com/harveyhang/ztreeDeptSelect

需要的朋友,請直接從github下載源碼。

后台請求數據使用ASP.NET完成,基於.NET Framework4.0。插件將會不斷的完善中,第一次分享代碼至github,希望園友們支持~

使用詳解

1.修改代碼獲取部門數據來源,即重新組織DeptDialogDataHandler.ashx的代碼。源代碼中,.ashx只是示例,是靜態數據,是假定查詢結果返回的數據;

   通常情況下部門數據來自數據庫,所以請根據實際項目來更改獲取部門數據的代碼。

2.部門樹依賴於zTree(一款部門樹插件),插件依賴於jQuery。所以請確保項目中有jquery和zTree的文件。具體請參考demo文件夾下的index.html文件和

   src文件夾下的deptDialog.html文件。

3.目前插件提供三種使用方法:簡單調用,設置默認值,設置參數 ;三種使用方法在demo\index.html都有說明。

部門數據的來源

加載部門樹的前台代碼:

$(document).ready(function () {
            var zNodes;
            //assign root data to zNodes.
            $.ajax({
                url: 'DeptDialogDataHandler.ashx',
                type: 'post',
                dataType: 'json',
                async: false,
                data: { 'ajaxMethod': 'GetRootData' },
                success: function (data) {
                    zNodes = data;
                }
            });

            //tree setting
            var setting = {
                async: {
                    enable: true, 
                    url: "DeptDialogDataHandler.ashx",
                    autoParam: ["id"], // Parameters of the parent node attribute that is automatically committed when the asynchronous load is loaded
                    otherParam: ["ajaxMethod", 'AsyncCurrentNodeChildren'], //ajax request parameters
                    type: 'post',
                    dataType: 'json'
                },
                view: {
                    showIcon: true,
                    dblClickExpand: false
                },
                showLine: true, // show ztree connect line
                data: {  //Using pId to identify the relationship between father and son 
                    simpleData: {
                        enable: true
                    }
                },
                callback: { //callback function.
                    onDblClick: zTreeOnDblClick,
                    asyncSuccess: zTreeOnAsyncSuccess
                }
            };
            //init ztree.
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });

handler文件的后台代碼:

<%@ WebHandler Language="C#" Class="DeptDialogDataHandler" %>

using System;
using System.Web;
using Newtonsoft.Json;

/// <summary>
/// Ajax Data Handler.
/// Author: https://github.com/harveyhang
/// Tips:Modify code to apply your own business...
/// </summary>
public class DeptDialogDataHandler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        //static data for test,this is the depts data...
        var depts = new[]{ 
            new {deptId = 0, deptName = "All Depts", parentDeptId = -1 },
            new {deptId = 1, deptName = "Technology Dept", parentDeptId = 0 },
            new {deptId = 2, deptName = "Software Dept", parentDeptId = 1 },
            new {deptId = 3, deptName = "Hardware Dept", parentDeptId = 1 },
            new {deptId = 4, deptName = "Human Resource Dept", parentDeptId = 0 } 
        };
        //convert data type to ztree 
        //... convert process is omitted
        /**
         * data convert instruction:
         * the previous code section has three common properties:deptId,deptName,parentDeptId ,
         * which was converted to these properties under:        id    ,name    ,pId
         * if department node has child,set isParent=true;else,set isParent=false;
         **/
        var zTreeDepts = new[] { 
            new {id = 0, name = "All Depts", pId = -1, isParent=true },
            new {id = 1, name = "Technology Dept", pId = 0, isParent=true },
            new {id = 2, name = "Software Dept", pId = 1, isParent=false },
            new {id = 3, name = "Hardware Dept", pId = 1, isParent=false },
            new {id = 4, name = "Human Resource Dept", pId = 0, isParent=false } 
        };
        
        try
        {
            string ajaxMethod = context.Request["ajaxMethod"].ToString();//get ajax method
            System.Reflection.MethodInfo method = this.GetType().GetMethod(ajaxMethod);
            if (method != null)
                method.Invoke(this, new object[] { context });//execute method
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            context.Response.End();
        }
    }
 
    /// <summary>
    /// async load children
    /// </summary>
    /// <param name="context"></param>
    public void AsyncCurrentNodeChildren(HttpContext context)
    {
        try
        {
            int id = int.Parse(context.Request.Params["id"]);
            var childrenData = new[] { 
                new {id = 1, name = "Technology Dept", pId = 0, isParent=true },
                new {id = 4, name = "Human Resource Dept", pId = 0, isParent=false } 
            };
            switch(id)
            {//suppose the data was getted
                case 0:
                    break;
                case 1:
                    childrenData = new[] { 
                        new {id = 2, name = "Software Dept", pId = 1, isParent=false },
                        new {id = 3, name = "Hardware Dept", pId = 1, isParent=false }
                    };
                    break;
                case 2:
                case 3:
                case 4:
                    childrenData = null;
                    break;
            }
            context.Response.Write(JsonConvert.SerializeObject(childrenData));
        }
        catch (Exception)
        {
            throw;
        }
    }
    
    /// <summary>
    /// root data
    /// </summary>
    /// <param name="context"></param>
    public void GetRootData(HttpContext context)
    {
        try
        {
            //suppose the data was getted
            var root = new { id = 0, name = "All Depts", pId = -1, isParent = true };
            context.Response.Write(JsonConvert.SerializeObject(root));
        }
        catch (Exception)
        {
            throw;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
View Code

此部分可以改為其它網頁語言,如php,java等。因為插件是前台通用的 ,后台數據可以根據實際需要定制。

總結

目前此插件尚有一個未修復的bug:“用Google Chrome瀏覽器時,部門窗口無法彈出”。因Chrome已阻止了js的showModalDialog方法。

IE或火狐等主流瀏覽器尚未發現有bug。當然,歡迎廣大園友批評指正。

由於是上github的項目,代碼注釋全部為本人"手寫"的英文。本人英語水平一般,這蹩腳的英語,,,還望諸位見諒~

如果各位覺得github上的英文描述不清晰,或者您對此插件有任何建議,歡迎留言一起交流~

最后,

希望本文對你有幫助。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM