Dtree web page tree menu and transfer object set to js, dynamic node generation

Source: Internet
Author: User

On the winform side, tree menus are very useful and convenient, so I want to put a tree menu on the page. I chose the dtree tool. There are still many ways to implement the page tree menu on the network. However, I think this tool is easy to use, and the configuration is relatively simple and can be used quickly. Dtree is pure js, so you do not need to import the jar package, and the configuration only needs to be configured in js. In addition, there are many improved versions on the network that have been modified by experts and added the checkbox, which is more convenient. In the development process, the most difficult thing is Data Interaction. Because dtree is pure js, there is no way to interact with the background. My approach is to first interact with the background, pass the data to the page, and then pass it to js. The data transmitted to the page in the background is spliced into a string, then cut in js, and the data is integrated into an array.
Background Data Processing code:
Copy codeThe Code is as follows:
Codepublic String GetLinkManByDID (){
Try {
Directories = this. directoryService. GetAllDirecoty ();
SelectlinkMans = this. linkManService. GetAllLinkMans ();
String direStringstring = "";
String linkString = "";
For (int I = 0; I <directories. size (); I ++ ){
If (I <directories. size ()-1 ){
DireStringstring + = directories. get (I). getID () + "-" + directories. get (I). getDirectoryName () + "+ ";
}
Else {
DireStringstring + = directories. get (I). getID () + "-" + directories. get (I). getDirectoryName ();
}
}
For (int I = 0; I <selectlinkMans. size (); I ++ ){
If (I <selectlinkMans. size ()-1 ){
LinkString + = selectlinkMans. get (I ). getDirectory (). getID () + "-" + selectlinkMans. get (I ). getName () + "-" + selectlinkMans. get (I ). getPhoneNum () + "+ ";
}
Else {
LinkString + = selectlinkMans. get (I ). getDirectory (). getID () + "-" + selectlinkMans. get (I ). getName () + "-" + selectlinkMans. get (I ). getPhoneNum ();
}
}
ActionContext. getContext (). getSession (). put ("directories", direStringstring );
ActionContext. getContext (). getSession (). put ("allLinkMans", linkString );
} Catch (Exception e ){
E. printStackTrace ();
}
Return SUCCESS;
}

I use s2sh, so the data is stored in the session
ActionContext. getContext (). getSession (). put (key, value)
Then the page will get the data:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var linkmans = [];
Var dires = [];
// Linkmans = "$ {directories}". replace ('[', ''). replace (']',''). split (',');
Linkmans = "$ {allLinkMans}". split (',');
Dires = "$ {directories}". split (',');
Treeload (linkmans [0], dires [0]);
</Script>

Treeload is a method in my own js file.
Js:
Copy codeThe Code is as follows:
Codefunction treeload (linkmans, dires ){
Var linklist = String2linklist (linkmans );
Var direslist = String2direlist (dires );
D = new dTree ('D ','./');
D. config. checkbox = true; // display checkbox
D. config. objValueId = 'phonenums ';
D. icon. root = 'images/hr/home.png ',
D. icon. folder = 'images/hr/group.gif ',
D. icon. folderOpen = 'images/hr/group.gif ',
D. icon. node = 'images/hr/nan.gif ',
D. add (0,-1, 'contacts ', null );
Var int = 0;
Var direids = new Array ();
Var direpid = new Array ();
For (int; int <direslist. length; int ++ ){
D. add (int + 1, 0, direslist [int]. name, false );
Direids. push (direslist [int]. id );
Direpid. push (int + 1 );
}
D. add (int + 1, 0, 'all contacts ', false );
Direpid. push (int + 1 );
For (var int2 = 0; int2 <linklist. length; int2 ++ ){
For (var int3 = 0; int3 <direpid. length-1; int3 ++ ){
If (linklist [int2]. did = direids [int3])
{
Int ++;
D. add (int + 1, direpid [int3], linklist [int2]. name, false, linklist [int2]. phone );
}
}
}
For (var int4 = 0; int4 <linklist. length; int4 ++ ){
Int ++;
D. add (int + 1, direpid [direpid. length-1], linklist [int4]. name, false, linklist [int4]. phone );
}

Document. write (d );
}
Function String2linklist (linkmans ){
Var linkarray = new Array ();
Var a = linkmans. split ('+ ');
// Alert (a [0]);
For (var int = 0; int <a. length; int ++ ){
Var B = a [int]. split ('-');
// Alert (B [2]);
Linkarray. push (new linkman (B [0], B [1], B [2]);
}
Return linkarray;
}
Function String2direlist (dires ){
Var direlist = new Array ();
Var a = dires. split ('+ ');
For (var int = 0; int <a. length; int ++ ){
Var B = a [int]. split ('-');
// Alert (B [1]);
Direlist. push (new dire (B [0], B [1]);
}
Return direlist;
}
Function linkman (Did, name, phone ){
This. did = Did;
This. name = name;
This. phone = phone;
}
Function dire (id, name ){
This. id = id;
This. name = name;
}

Finally,

Js of the dtree I changed:
Copy codeThe Code is as follows:
// Node object
Function Node (id, pid, name, checked, value, icon, url, title, target, iconOpen, open ){
This. id = id;
This. pid = pid;
This. name = name;
// Whether to add a check box to the node and set the selected status. Optional values: true (selected), false (not selected), and null (not added ).
This. checked = null? Null :( checked | false );

This. value = value; // Add the value attribute. Select the check box and the value is obtained in the input box.
This. url = url;
This. title = title;
This.tar get = target;
This. icon = icon;
This. iconOpen = iconOpen;
This. _ io = open | false;
This. _ is = false;
This. _ ls = false;
This. _ hc = false;
This. _ ai = 0;
This. _ p;
};
// Tree object
Function dTree (objName, path ){
// Path
This. path = path | '';
// Load the css file
This.loadCssFile(this.path+'dtree.css ');
This. config = {
Target: null,
FolderLinks: true,
UseSelection: true,
UseCookies: true,
UseLines: true,
UseIcons: true,
UseStatusText: false,
CloseSameLevel: false,
InOrder: false,
// Whether to display the check box, true to display, false not to display
Checkbox: false,
ObjValueId :''
}
This. icon = {
Root: this. path + 'images/img/base.gif ',
Folder: this. path + 'images/img/folder.gif ',
FolderOpen: this. path + 'images/img/folderopen.gif ',
Node: this. path + 'images/img/page.gif ',
Empty: this. path + 'images/img/empty.gif ',
Line: this. path + 'images/img/line.gif ',
Join: this. path + 'images/img/join.gif ',
JoinBottom: this. path + 'images/img/joinbottom.gif ',
Plus: this. path + 'images/img/plus.gif ',
PlusBottom: this. path + 'images/img/plusbottom.gif ',
Minus: this. path + 'images/img/minus.gif ',
MinusBottom: this. path + 'images/img/minusbottom.gif ',
NlPlus: this. path + 'images/img/nolines_plus.gif ',
NlMinus: this. path + 'images/img/nolines_minus.gif'
};
This. obj = objName;
This. aNodes = [];
This. aIndent = [];
This. root = new Node (-1 );
This. selectedNode = null;
This. selectedFound = false;
This. completed = false;
};
// Set the selected node
DTree. prototype. checkedNodes = function (){
If (this. config. objValueId = ''){
Return;
}
Var val = document. getElementById (this. config. objValueId). value;
If (val = ''){
Return;
}
Val = val. split (',');
Var o = null;
For (var I = 0; I <val. length; I ++ ){
O = document. getElementById ('cbx _ '+ this. obj + val [I]);
If (o ){
O. checked = true;
}
}
};
// Automatically enter the value of the selected item in the input box
DTree. prototype. update = function (){
If (this. config. objValueId = ''){
Return;
}
Var cbx = null, v = [];
// V. push (aa );
Var ns = this. aNodes;
For (var I = 0; I <ns. length; I ++ ){
Cbx = document. getElementById ('cbx _ '+ this. obj + ns [I]. id );
If (cbx ){
If (cbx. checked ){
If (ns [I]. pid! = '0 '){
V. push (cbx. value); // you can select the contact and obtain the number by changing the id of the node to value.
}
}
}
}
Document. getElementById (this. config. objValueId). value = v. join ();
};
// Load the css file
DTree. prototype. loadCssFile = function (file ){
Try {
Var head = document. getElementsByTagName ("head") [0];
Var links = head. getElementsByTagName ('link ');
Var I = 0;
For (var I = 0; I <links. length; I ++ ){
If (links [I]. getAttribute ('href '). toLowerCase (). indexOf (file. toLowerCase ()>-1 ){
Return;
}
}
Var f = document. createElement ("link ");
F. setAttribute ("rel", "stylesheet ");
F. setAttribute ("type", "text/css ");
F. setAttribute ("href", file );
Head. appendChild (f );
} Catch (ex ){
Alert ('error in loading css file: '+ ex. message );
}
};
// Adds a new node to the node array
DTree. prototype. add = function (id, pid, name, checked, value, icon, url, title, target, iconOpen, open ){
This. aNodes [this. aNodes. length] = new Node (id, pid, name, checked, value, icon, url, title, target, iconOpen, open );
};
// Open/close all nodes
DTree. prototype. openAll = function (){
This. oAll (true );
};
DTree. prototype. closeAll = function (){
This. oAll (false );
};
// Outputs the tree to the page
DTree. prototype. toString = function (){
Var str = '<div class = "dtree" id = "dTree _' + this. obj + '"> \ n ';
If (document. getElementById ){
If (this. config. useCookies) this. selectedNode = this. getSelected ();
Str + = this. addNode (this. root );
} Else str + = 'browser not supported .';
Str + = '</div> ';
If (! This. selectedFound) this. selectedNode = null;
This. completed = true;
Return str;
};
// Creates the tree structure
DTree. prototype. addNode = function (pNode ){
Var str = '';
Var n = 0;
If (this. config. inOrder) n = pNode. _ ai;
For (n; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. pid = pNode. id ){
Var cn = this. aNodes [n];
Cn. _ p = pNode;
Cn. _ ai = n;
This. setCS (cn );
If (! Cn.tar get & this.config.tar get) cn.tar get = this.config.tar get;
If (cn. _ hc &&! Cn. _ io & this. config. useCookies) cn. _ io = this. isOpen (cn. id );
If (! This. config. folderLinks & cn. _ hc) cn. url = null;
If (this. config. useSelection & cn. id = this. selectedNode &&! This. selectedFound ){
Cn. _ is = true;
This. selectedNode = n;
This. selectedFound = true;
}
Str + = this. node (cn, n );
If (cn. _ ls) break;
}
}
Return str;
};
// Creates the node icon, url and text
DTree. prototype. node = function (node, nodeId ){
Var str = '<div class = "dTreeNode">' + this. indent (node, nodeId );
If (this. config. useIcons ){

If (! Node. icon) node. icon = (this. root. id = node. pid )? This. icon. root: (node. pid = 0 )? This. icon. folder: this. icon. node );
// The node. pid = 0 condition is changed by myself. If there are no one in the group, use the icon of the group instead of the icon of the contact. You can try it on your own.
If (! Node. iconOpen) node. iconOpen = (node. _ hc )? This. icon. folderOpen: this. icon. node;
If (this. root. id = node. pid ){
Node. icon = this. icon. root;
Node. iconOpen = this. icon. root;
}
Str + = ' ';
}
/*** Add checkbox display ***/
If (this. config. checkbox & node. checked! = Null ){
Str + = '<input' + (node. checked? 'Checked = \ "checked \" ': '') + 'onclick = \" javascript:' + this. obj + (node. _ hc & node. pid! = This. root. id? '. O ('+ nodeId + ')':'. update () ') +'; \ "type = \" checkbox \ "value = \" '+ node. value + '\ "name = \" cbx _' + this. obj + '\ "id = \" cbx _' + this. obj + nodeId + '\ "title = \"' + node. name + '\ "\/> ';
}
If (node. url ){
Str + = '<a id = "s' + this. obj + nodeId + '" class = "' + (this. config. useSelection )? (Node. _ is? 'Nodesel ': 'node') +' "href =" '+ node. url + '"';
If (node. title) str + = 'title = "'+ node. title + '"';
If (node.tar get) str + = 'target = "'+ node.tar get + '"';
If (this. config. useStatusText) str + = 'onmouseover = "window. status = \ ''+ node. name + '\'; return true; "onmouseout =" window. status = \ '; return true ;"';
If (this. config. useSelection & (node. _ hc & this. config. folderLinks) |! Node. _ hc ))
Str + = 'onclick = "javascript: '+ this. obj +'. s ('+ nodeId + ');"';
Str + = '> ';
}
Else if ((! This. config. folderLinks |! Node. url) & node. _ hc & node. pid! = This. root. id)
Str + = '<a href = "javascript:' + this. obj + '. o (' + nodeId + ');" class = "node"> ';
Str + = node. name;
If (node. url | ((! This. config. folderLinks |! Node. url) & node. _ hc) str + = '</a> ';
Str + = '</div> ';
If (node. _ hc ){
Str + = '<div id = "D' + this. obj + nodeId + '"class =" clip "style =" display:' + (this. root. id = node. pid | node. _ io )? 'Block': 'None') + '; "> ';
Str + = this. addNode (node );
Str + = '</div> ';
}
This. aIndent. pop ();
Return str;
};
// Adds the empty and line icons
DTree. prototype. indent = function (node, nodeId ){
Var str = '';
If (this. root. id! = Node. pid ){
For (var n = 0; n <this. aIndent. length; n ++)
Str + = ' ';
(Node. _ ls )? This. aIndent. push (0): this. aIndent. push (1 );
If (node. _ hc ){
Str + = '<a href = "javascript:' + this. obj + '. o ('+ nodeId +'); "> If (! This. config. useLines) str + = (node. _ io )? This. icon. nlMinus: this. icon. nlPlus;
Else str + = (node. _ io )? (Node. _ ls & this. config. useLines )? This. icon. minusBottom: this. icon. minus): (node. _ ls & this. config. useLines )? This. icon. plusBottom: this. icon. plus ));
Str + = '"alt =" "/> </a> ';
} Else str + = ' ';
}
Return str;
};
// Checks if a node has any children and if it is the last sibling
DTree. prototype. setCS = function (node ){
Var lastId;
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. pid = node. id) node. _ hc = true;
If (this. aNodes [n]. pid = node. pid) lastId = this. aNodes [n]. id;
}
If (lastId = node. id) node. _ ls = true;
};
// Returns the selected node
DTree. prototype. getSelected = function (){
Var sn = this. getCookie ('cs '+ this. obj );
Return (sn )? Sn: null;
};
// Highlights the selected node
DTree. prototype. s = function (id ){
If (! This. config. useSelection) return;
Var cn = this. aNodes [id];
If (cn. _ hc &&! This. config. folderLinks) return;
If (this. selectedNode! = Id ){
If (this. selectedNode | this. selectedNode = 0 ){
EOld = document. getElementById ("s" + this. obj + this. selectedNode );
EOld. className = "node ";
}
ENew = document. getElementById ("s" + this. obj + id );
ENew. className = "nodeSel ";
This. selectedNode = id;
If (this. config. useCookies) this. setCookie ('cs '+ this. obj, cn. id );
}
};
// Toggle Open or close
DTree. prototype. o = function (id ){
Var cn = this. aNodes [id];
This. nodeStatus (! Cn. _ io, id, cn. _ ls );
Cn. _ io =! Cn. _ io;
If (this. config. closeSameLevel) this. closeLevel (cn );
If (this. config. useCookies) this. updateCookie ();
// Update the selected value if (this. config. objValueId! = '')
This. update ();
};
// Open or close all nodes
DTree. prototype. oAll = function (status ){
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. _ hc & this. aNodes [n]. pid! = This. root. id ){
This. nodeStatus (status, n, this. aNodes [n]. _ ls)
This. aNodes [n]. _ io = status;
}
}
If (this. config. useCookies) this. updateCookie ();
};
// Opens the tree to a specific node
DTree. prototype. openTo = function (nId, bSelect, bFirst ){
If (! BFirst ){
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. id = nId ){
NId = n;
Break;
}
}
}
Var cn = this. aNodes [nId];
If (cn. pid = this. root. id |! Cn. _ p) return;
Cn. _ io = true;
Cn. _ is = bSelect;
If (this. completed & cn. _ hc) this. nodeStatus (true, cn. _ ai, cn. _ ls );
If (this. completed & bSelect) this. s (cn. _ ai );
Else if (bSelect) this. _ sn = cn. _ ai;
This. openTo (cn. _ p. _ ai, false, true );
};
// Closes all nodes on the same level as certain node
DTree. prototype. closeLevel = function (node ){
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. pid = node. pid & this. aNodes [n]. id! = Node. id & this. aNodes [n]. _ hc ){
This. nodeStatus (false, n, this. aNodes [n]. _ ls );
This. aNodes [n]. _ io = false;
This. closeAllChildren (this. aNodes [n]);
}
}
}
// Closes all children of a node
DTree. prototype. closeAllChildren = function (node ){
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. pid = node. id & this. aNodes [n]. _ hc ){
If (this. aNodes [n]. _ io) this. nodeStatus (false, n, this. aNodes [n]. _ ls );
This. aNodes [n]. _ io = false;
This. closeAllChildren (this. aNodes [n]);
}
}
}
// Change the status of a node (open or closed)
DTree. prototype. nodeStatus = function (status, id, bottom ){
Try {
EDiv = document. getElementById ('D' + this. obj + id );
EJoin = document. getElementById ('J' + this. obj + id );
// *** Select
If (this. config. checkbox ){
Cbx = document. getElementById ('cbx _ '+ this. obj + id );
Cbx. checked = status;
CbxChild = eDiv. getElementsByTagName ('input ');
For (var I = 0; I <cbxChild. length; I ++ ){
CbxChild [I]. checked = status;
}
}
// *** Select
If (this. config. useIcons ){
EIcon = document. getElementById ('I' + this. obj + id );
EIcon. src = (status )? This. aNodes [id]. iconOpen: this. aNodes [id]. icon;
}
EJoin. src = (this. config. useLines )?
(Status )? (Bottom )? This. icon. minusBottom: this. icon. minus) :( (bottom )? This. icon. plusBottom: this. icon. plus )):
(Status )? This. icon. nlMinus: this. icon. nlPlus );
EDiv. style. display = (status )? 'Block': 'none ';
} Catch (ex ){
}
};
// [Cookie] Clears a cookie
DTree. prototype. clearCookie = function (){
Var now = new Date ();
Var yesterday = new Date (now. getTime ()-1000*60*60*24 );
This. setCookie ('co' + this. obj, 'cookievalue ', yesterday );
This. setCookie ('cs '+ this. obj, 'cookievalue', yesterday );
};
// [Cookie] Sets value in a cookie
DTree. prototype. setCookie = function (cookieName, cookieValue, expires, path, domain, secure ){
Document. cookie =
Escape (cookieName) + '=' + escape (cookieValue)
+ (Expires? '; Expires =' + expires. toGMTString ():'')
+ (Path? '; Path =' + path :'')
+ (Domain? '; Domain =' + domain :'')
+ (Secure? '; Secure ':'');
};
// [Cookie] Gets a value from a cookie
DTree. prototype. getCookie = function (cookieName ){
Var cookieValue = '';
Var posName = document. cookie. indexOf (escape (cookieName) + '= ');
If (posName! =-1 ){
Var posValue = posName + (escape (cookieName) + '='). length;
Var endPos = document. cookie. indexOf (';', posValue );
If (endPos! =-1) cookieValue = unescape (document. cookie. substring (posValue, endPos ));
Else cookieValue = unescape (document. cookie. substring (posValue ));
}
Return (cookieValue );
};
// [Cookie] Returns ids of open nodes as a string
DTree. prototype. updateCookie = function (){
Var str = '';
For (var n = 0; n <this. aNodes. length; n ++ ){
If (this. aNodes [n]. _ io & this. aNodes [n]. pid! = This. root. id ){
If (str) str + = '.';
Str + = this. aNodes [n]. value;
}
}
This. setCookie ('co' + this. obj, str );
};
// [Cookie] Checks if a node id is in a cookie
DTree. prototype. isOpen = function (id ){
Var aOpen = this. getCookie ('co' + this. obj). split ('.');
For (var n = 0; n <aOpen. length; n ++)
If (aOpen [n] = id) return true;
Return false;
};
// If Push and pop is not implemented by the browser
If (! Array. prototype. push ){
Array. prototype. push = function array_push (){
For (var I = 0; I <arguments. length; I ++)
This [this. length] = arguments [I];
Return this. length;
}
};
If (! Array. prototype. pop ){
Array. prototype. pop = function array_pop (){
LastElement = this [this. length-1];
This. length = Math. max (this. length-1, 0 );
Return lastElement;
}
};

You can use it for reference and try a small project by yourself. dtree is good.

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.