JavaScript processing data Complete the left level two menu building

Source: Internet
Author: User
Tags log log

The back-end management framework we applied to the project was basically the same, with a level two menu on the left, a click on the selected menu, and a corresponding page on the right. I put the front-end page encapsulation data process, although not necessarily suitable for all management pages, only as a case to reference, just hope you can understand the principle of implementation is good.

  The menu on the left is built:

1, first, we need to apply the menu to import the database.

The following is the data I imported:

    

Depending on my business needs, I need four parent menus, so I set their PID field to 0, and the PID field of the submenu corresponds to the ID of the parent menu, which is important. The URL field is the address path that appears on the right page when you click the menu. The Status Status field represents whether the state of the current menu is available, the 0 I set here is available, 1 is unavailable, and you'll see later. The Order_num field is not available here for the time being.

    2. Encapsulates a constructor to read and create a level two menu

In order not to make this case too cumbersome, I try to reduce the amount of code without considering the flexibility of the constructor. Assuming only for this case, the encapsulated function is as follows:

function Menutree (id,url) {this.id = ID;    This.url = URL;    this. $Div = null;    this. $curA = null;    This.inittree ();     }menutree.prototype.inittree = function () {var = this;    The container on the left-hand menu, which defines this based on the ID of the element. $Div = $ ("#" +this.id);        if (this. $Div. length = = 0) {Alert ("Menu initial container failed");    Return    }//Click on the agent of the method, click on this container will use This.treeclick defined method to proxy this. $Div. Click ($.proxy (This.treeclick,this));    Send Request $.post (this.url,function (data) {Self.createtreemenu (data.list) to the set menu address; }, "json")}menutree.prototype.createtreemenu = function (list) {///If the data is not read, or if the data length is 0, the container displays a temporary no menu if (!list| |        List.length = = 0) {this. $Div. html ("no Menu");    Return    }//Declare an empty object to hold the menu information created var rootnodes = {};    var len = list.length;    var node = null;    var curnodeid= "";        for (var i=0;i<len;i++) {node = list[i];        When the Read menu status is 1 o'clock, the menu is unavailable, skipping if (node.status== ' 1 ') continue;        var id = node.id;    var name = Node.name;    var url = node.url;        var pid = node.pid; When this data pid is 0 o'clock, create this data for parent menu if (pid = = "0") {Rootnodes[id] = $ ("<div class= ' Lefttreemenu haschildren ' >            <leftMenuTitle> "+name+" </leftMenuTitle></div> ");        Continue        }//The PID of the submenu is the ID of the parent menu, so here Rootnodes[pid] is the above rootnodes[id] var $pnode = rootnodes[pid]; After the submenu is created, you add the ID and URL as custom attributes to the element, which is followed by var $a = $ ("<lefttreenode id= ' lefttreelink_" +id+ ">" +name+ "</lefttree        Node> "). attr (" id ", id). attr (" url ", url);        $pnode. Append ($a);            Here is a skip, the next article says if (Fromuri && (Url==fromuri)) {this. $curA = $a. AddClass ("Currenta");            $pnode. addclass ("Currentmenu"). Removeclass ("Hidechildren");        Mybar.freshtag (Id,name,url);    }} var df = Document.createdocumentfragment (); The purpose of the for (key in Rootnodes) {//appendchild is native JS usage//[0] is to convert the JQ object to a DOM object Df.appendchild (Rootnodes[key][0]    ); } (tHis. $Div) [0].appendchild (DF);}    MenuTree.prototype.treeClick = function (e) {//click event, which uses the conversion of the DOM and JQ var target = E.target;    var nodeName = Target.nodename; If you click on the parent menu, you can toggle the class name to show and hide the submenu if (NodeName = = "Leftmenutitle") {$ (target). Parent (). Switchclass ("Hidechildren"        );    Return    }//If the submenu is clicked, the data of the submenu is processed if (nodeName = = "Lefttreenode") {This.freshtag ($ (target));    }}menutree.prototype.changecurnode = function ($e) {//If the clicked is the same as the selected one, return if (this. $curA = = $e) return; If this. $curA exists, remove the previous class name Currenta and the submenu hides the if (this. $curA) {this. $curA. Removeclass ("Currenta"). Parent (). Removeclass    ("Currentmenu");    }//Just click the Add class name Currenta and display the submenu of this. $curA = $e. addclass ("Currenta"); $e. Parent (). addclass ("Currentmenu"). Removeclass ("Hidechildren");}    MenuTree.prototype.freshTag = function ($e) {//Handle clicked Element This.changecurnode ($e);    Remove the URL that is bound to the element in the var url = $e. attr ("url");        if (Url.indexof ("http") ==0) {window.open (URL);Return  }//This will be said in the next article, here is the creation of the right mybar and URL page display information Mybar.freshtag ($e. attr ("id"), $e. html (), URL);}

    3, the JSP page call

The JSP page is simple, creating a left container ID of "Lefttree" and then:

var lefttree = new Menutree ("Lefttree", "<c:url value= '/menu/getmenutree '/>");

I explain that this article only explains the reading and creation of the menu on the left, as well as clicking on the show page to prepare for the next article.

    4, the processing process of the background    

Package Cn.wangze.controller;import Java.util.list;import Javax.annotation.resource;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.sessionattributes;import Cn.wangze.service.syscacheservice;import Cn.wangze.service.sysmenuservice;import Cn.wangze.domain.sysmenu;//import cn.wangze.service.sysmenuservice;// Import cn.wangze.utils.AuthUtils; @Controller @requestmapping ("/menu") @SessionAttributes ("Sysuser") public class        SysMenuController01 extends basecontroller{log log = Logfactory.getlog (GetClass ()); Inject the service of the menu into the controller @Resource private sysmenuservice<sysmenu> sysmenuservice;        If the menu is fixed, we can put the data into the cache, so that we do not have to request from the database every time @Autowired private syscacheservice syscacheservice; @RequestMapping (value = "/{pagepath}/{pagename}") Public String gomenupage (@PathVariable string Pagepath, @PathVariabl        e String pagename,httpservletrequest request) {Setfromuri (request);    Return "/" + Pagepath + "/" + pageName; } @RequestMapping (value = "/getmenutree") public void GetMenu (HttpServletResponse response,httpsession session)        {//Call Syscacheservice's Querymenulist method to fetch data list<sysmenu> List = Syscacheservice.querymenulist ();        Log.debug ("Total menu:" + list);        if (list = = null) return;    You can refer to the blog post I sent earlier, encapsulating the method of returning data in Basecontroller inside Sendjsonlist (list, response); }}

Service and domain layer also has the mapper layer of code I will not send, is the operation of the query, because there is no control of the role permissions, so it is not much difficulty.

  5, the effect after the creation of a good

   

Next article we explain the process of clicking on the submenu and displaying the corresponding address on the right.

JavaScript processing data Complete the left level two menu building

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.