javascript與jquery混合而成的動態無限樹形結構的菜單

來源:互聯網
上載者:User

前台代碼如下:主要就是ajax的實現

  <script type="text/javascript" language="javascript">
$(initMenuInfo);
     function initMenuInfo()
      {
      var tbody = "";
      $.ajax({
      type: "GET",
      dataType: "json",
      url: 'Tree.aspx',
      data: "s=1", 
      error: function(){
           tbody="資料載入失敗";
           $("#menu").append(tbody);
          },
                success: function(data) {
                    var menus = data.menuModels;
                    $.each(menus, function(i, menu) {
                        if(menu!=null)
                        {
                        var divstr="div"+menu.ModuleId;
                        var trs = "";
                        trs +='<div id="'+divstr+'">';
                        trs += '<a href="#" class="menuover"  title="' + menu.ModuleName + '" onclick="node

                        ('+menu.ModuleId+');">';
                        trs +=menu.ModuleName+'</a>';
                        trs +='</div>';
                        tbody += trs;
                        }
                    });
                     if(tbody=="")
                        tbody="暫無資料";
                    $("#menu").addClass("hasload").append(tbody);
                    },
                 complete: function(XMLHttpRequest, textStatus){
                
                }
    
      });
      }
     function node(id){
      var divId="div"+id.toString();
      var tbody1 = "";
      if(!$("#"+divId+"").hasClass("hasload"))
      {
      $.ajax({
      type: "GET",
      dataType: "json",
      url: 'Tree.aspx',
      data: "f=2&id=" + id,
      error: function(){
           tbody1="資料載入失敗";
          $("#"+divId+"").append(tbody1);
          },
                success: function(data) {
                    var menus = data.menuModels;
                    $.each(menus, function(i, menu) {
                        if(menu!=null)
                        {
                        var divstr="div"+menu.ModuleId;
                        var trs1 = "";
                        trs1+='<div class="menuover" id="'+divstr+'">';
                        trs1 += '<a href="#"  title="' + menu.ModuleName + '" onclick="node

                       ('+menu.ModuleId+');">';
                        trs1 +=menu.ModuleName+'</a>';
                        trs1 +='</div>';
                        tbody1 += trs1;
                        }
                    });
                     if(tbody1!="")
                    $("#"+divId+"").addClass("hasload").append(tbody1);
                    },
                 complete: function(XMLHttpRequest, textStatus){
                
                }
    
      });
      }
      else
      {
        $("#"+divId+">div").toggle();
        $("#"+divId+">div>div").hide();
    // if(document.getElementById(divId).getElementsByTagName("div")[0].className=="menuover")
    // {
    // alert("aa");
    // for(j=0; j<document.getElementById(divId).getElementsByTagName("div").length; j++)
    // {
     //var obj=document.getElementById(divId).getElementsByTagName("div")[j];
    // obj.className=obj.className.replace("menuover", "menuhide");
    // }
   
     //}
    // else
     //{
    // for(j=0; j<document.getElementById(divId).getElementsByTagName("div").length; j++)
    // {
    // var obj=document.getElementById(divId).getElementsByTagName("div")[j];
    // obj.className=obj.className.replace("menuhide", "menuover");
  
    //}
    //}
    
      }
            }

    </script>

    <div id="menu" >
    </div>

後台代碼如下:主要是構建json對象

 protected void Page_Load(object sender, EventArgs e)
    {
      if( Request.QueryString["s"] == "1")
        {
            GetFirstMenu();
        }
      if (Request.QueryString["f"] == "2")
      {
          int nodeId = int.Parse(Request.QueryString["id"]);
          GetLastMenu(nodeId);
      }
    }
    public void GetFirstMenu()
    {

        DataSet ds = new DataSet();
        string strsql = "select * from Menu where ParentID=0";
        ds = DbHelper.Query(strsql);
        if(ds!=null)
        {
        List<MenuModel> MenuModels = new List<MenuModel>();
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            MenuModel menumodel = new MenuModel();
            menumodel.ModuleId = int.Parse(ds.Tables[0].Rows[i]["ModuleId"].ToString());
            menumodel.ModuleName = ds.Tables[0].Rows[i]["ModuleName"].ToString();
            menumodel.ParentID = int.Parse(ds.Tables[0].Rows[i]["ParentID"].ToString());
            menumodel.IsPage = bool.Parse(ds.Tables[0].Rows[i]["IsPage"].ToString());
            menumodel.UrlAddress = ds.Tables[0].Rows[i]["UrlAddress"].ToString();
            MenuModels.Add(menumodel);

        }
        string jsonstr = GetJsonStr(MenuModels);
        Response.Write(jsonstr);
        Response.End();
        }
    }
    public void GetLastMenu(int id)
    {

        DataSet ds = new DataSet();
        string strsql = "select * from Menu where ParentID='"+id+"'";
        ds = DbHelper.Query(strsql);
        if (ds != null)
        {
            List<MenuModel> MenuModels = new List<MenuModel>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                MenuModel menumodel = new MenuModel();
                menumodel.ModuleId = int.Parse(ds.Tables[0].Rows[i]["ModuleId"].ToString());
                menumodel.ModuleName = ds.Tables[0].Rows[i]["ModuleName"].ToString();
                menumodel.ParentID = int.Parse(ds.Tables[0].Rows[i]["ParentID"].ToString());
                menumodel.IsPage = bool.Parse(ds.Tables[0].Rows[i]["IsPage"].ToString());
                menumodel.UrlAddress = ds.Tables[0].Rows[i]["UrlAddress"].ToString();
                MenuModels.Add(menumodel);

            }

            string jsonstr = GetJsonStr(MenuModels);
            Response.Write(jsonstr);
            Response.End();
        }
    }
    public string GetJsonStr(List<MenuModel> MenuModels)
    {
        StringBuilder json = new StringBuilder();
        json.Append("{\"menuModels\":[");
        foreach (MenuModel model in MenuModels)
        {
            json.Append("{\"ModuleId\":\"" + model.ModuleId + "\",\"ModuleName\":\"" + model.ModuleName + 

          "\",\"ParentID\":\"" + model.ParentID + "\",\"IsPage\":\"" + model.IsPage + "\",\"UrlAddress\":\"" +  

           model.UrlAddress + "\"}");
           json.Append(","); 
        }
        return json.ToString().TrimEnd(',') + "]}";

    }
    public class MenuModel
    {
        public int ModuleId { get; set; }

        public string ModuleName { get; set; }

        public int ParentID { get; set; }

        public string UrlAddress { get; set; }

        public bool IsPage { get; set; }

    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.