JavaScript-javascript做一个简单的树结构

JavaScript-javascript做一个简单的树结构

虐人心 发布于 2017-06-24 字数 183 浏览 1109 回复 1

因为后台需要写一个树结构的展示下拉,
数据源最好是json结构的
最终我想说的是占用内存少点 效率点的,
尽量是大家测试用过的,网上的就别贴了
因为我这里也有好多...

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱自由 2017-07-26 1 楼

这个耗内存小一点,你试一试,
这个实现树的原理是根据json,
不断的生成ul li,
下面是一个简单的例子,
没有用innerHTML生成,
全是是创建节点来创建ul li,
所以创建节点碎片添加,
然后再一次性添加,
确实能提高速度...

<style type="text/css">
ul,li{
list-style: none outside none;
margin: 0;
overflow: hidden;
padding: 0;
}
#demo{
background-color: #F0FBEB;
}
#demo .root{
margin-left: -20px;
}
#demo ul{
padding-left: 20px;
}
#demo .folder{
background: url("../../i.png") repeat-y scroll 0 21px transparent;
}
#demo img{
background: url("../../i.png") no-repeat scroll 0 0 transparent;
border: medium none;
height: 20px;
vertical-align: top;
width: 20px;
}
#demo .tvicon-open{
background-position: -160px -40px;
}
#demo .tvdash-f{
background-position: -240px -40px;
}
#demo .tvdash-f-open{
background-position: -200px -40px;
}
#demo .tvdash-fl{
background-position: -100px -40px;
}
#demo .tvdash-fl-open{
background-position: -80px -40px;
}
#demo .tvdash-t{
background-position: -180px -40px;
}
#demo .tvdash-tl{
background-position: -60px -40px;
}
</style>
</head>
<body>
<div id='sss'></div>
<div id='demo'></div>
<script>
(function(doc,undefined){
var window = this;
window.Sys = function (ua){
var b = {
ie: /msie/.test(ua) && !/opera/.test(ua),
opera: /opera/.test(ua),
safari: /webkit/.test(ua) && !/chrome/.test(ua),
firefox: /firefox/.test(ua),
chrome: /chrome/.test(ua)
},vMark = "";
for (var i in b) {
if (b[i]) { vMark = "safari" == i ? "version" : i; break; }
}
b.version = vMark && RegExp("(?:" + vMark + ")[\/: ]([\d.]+)").test(ua) ? RegExp.$1 : "0";
b.ie6 = b.ie && parseInt(b.version, 10) == 6;
b.ie7 = b.ie && parseInt(b.version, 10) == 7;
b.ie8 = b.ie && parseInt(b.version, 10) == 8;
return b;
}(window.navigator.userAgent.toLowerCase());
window.Sys.ie6&&doc.execCommand("BackgroundImageCache", false, true);
window.$$ = function(Id){
return doc.getElementById(Id);
};
window.$c = function(name,parent){
var elem = doc.createElement(name);
parent&&parent.appendChild(elem);
return elem;
};
window.addListener = function(element,e,fn){
!element.events&&(element.events = {});
element.events[e]&&(element.events[e][addListener.guid++]=fn)||(element.events[e] = {'0':fn});
element.addEventListener?element.addEventListener(e,fn,false):element.attachEvent("on" + e,fn);
};
window.addListener.guid = 1;
window.removeListener = function(element,e,fn){
var handlers = element.events[e],type;
if(fn){
for(type in handlers)
if(handlers[type]===fn){
element.removeEventListener?element.removeEventListener(e,fn,false):element.detachEvent("on" + e,fn);
delete handlers[type];
}
}else{
for(type in handlers){
element.removeEventListener?element.removeEventListener(e,handlers[type],false):element.detachEvent("on" + e,handlers[type]);
delete handlers[type];
}
}
};
window.setStyle = function(e,o){
if(typeof o=="string")
e.style.cssText=o;
else
for(var i in o)
e.style[i] = o[i];
};
var slice = Array.prototype.slice;
window.Bind = function(object, fun) {
var args = slice.call(arguments).slice(2);
return function() {
return fun.apply(object, args);
};
};
window.BindAsEventListener = function(object, fun,args) {
var args = slice.call(arguments).slice(2);
return function(event) {
return fun.apply(object, [event || window.event].concat(args));
}
};
//copy from jQ
window.extend = function(){
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = true, options;
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
i = 2;
}
if ( typeof target !== "object" && Object.prototype.toString.call(target)!="[object Function]")
target = {};
for(;i<length;i++){
if ( (options = arguments[ i ]) != null )
for(var name in options){
var src = target[ name ], copy = options[ name ];
if ( target === copy )
continue;
if ( deep && copy && typeof copy === "object" && !copy.nodeType ){
target[ name ] = arguments.callee( deep, src || ( copy.length != null ? [ ] : { } ), copy );
}
else if(copy !== undefined)
target[ name ] = copy;
}
}
return target;
};
//copy from jQ
window.each = function ( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
args = Array.prototype.slice.call(arguments).slice(2);
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ],[name,object[ name ]].concat(args) ) === false )
break;
} else
for ( ; i < length; i++)
if ( callback.apply( object[ i ],[i,object[ i ]].concat(args)) === false ) //
break;
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
};
window.currentStyle = function(element){
return element.currentStyle || doc.defaultView.getComputedStyle(element, null);
};
window.objPos = function(elem){
var left = 0, top = 0, right = 0, bottom = 0,doc = elem ? elem.ownerDocument : doc;
if ( !elem.getBoundingClientRect || window.Sys.ie8 ) {
var n = elem;
while (n) { left += n.offsetLeft, top += n.offsetTop; n = n.offsetParent; };
right = left + elem.offsetWidth; bottom = top + elem.offsetHeight;
} else {
var rect = elem.getBoundingClientRect();
left = right = doc.documentElement.scrollLeft || doc.body.scrollLeft;
top = bottom = doc.documentElement.scrollLeft || doc.body.scrollLeft;
left += rect.left; right += rect.right;
top += rect.top; bottom += rect.bottom;
}
return { "left": left, "top": top, "right": right, "bottom": bottom };
};
window.hasClass = function(element, className){
return element.className.match(new RegExp('(\s|^)'+className+'(\s|$)'));
};
window.addClass = function(element, className){
!window.hasClass(element, className)&&(element.className += " "+className);
};
window.removeClass = function(element, className){
window.hasClass(element, className)&&(element.className = element.className.replace(new RegExp('(\s|^)'+className+'(\s|$)'),' '));
}
})(document);
//------------------------------------------------------------
(function(doc,undefined){
var win = this;
win.easyTree = function(){
this.init.apply(this,arguments);
};
win.easyTree.prototype = {
options : {
},
init : function(options){
this.deflaut = extend(this.options,options);
this.container = options.container;
this.data = options.data;
//根节点直接在这里生成
if(this.data.length>=1){
var ul = $c('ul',this.container),
self = this,
li;
each(this.data,function(i,o){
li = $c('li',ul);
li.className = 'root';
li.innerHTML = '<img src="http://images.cnblogs.com/cnblogs_com/wtcsy/294024/r_space.png" class="tvicon-open"><a href=" #">'+o.name+'</a>';
o.child
&&self.bulidTree(o.child,li,'t')
});
}
},
bulidTree : function(data,parent,first){
if(data.length===0)
return;
var ul = $c('ul',parent),
self = this,
len = data.length,
imgClassName,
li;
first
? ul.style.paddingLeft = '0px'
: ul.style.display = 'none';
each(data,function(i,o){
var isLast = (len-1)===i;
li = $c('li',ul);
li.className = 'folder'+(isLast?'l':'');
imgClassName = o.child
? isLast?'tvdash-fl':'tvdash-f'
: isLast?'tvdash-tl':'tvdash-t';
li.innerHTML = '<img src="http://images.cnblogs.com/cnblogs_com/wtcsy/294024/r_space.png" class="'+imgClassName+'"><a href=" #">'+o.name+'</a>';
img = li.getElementsByTagName('img')[0];
addListener(img,'click',BindAsEventListener(self,self.openOrClose,li,img));
o.child
&&self.bulidTree(o.child,li);
});
},
openOrClose : function(e,li,img){
var ul = li.getElementsByTagName('ul')[0];
if(ul){
ul.style.display = ul.style.display === 'none'?'':'none';
var name = img.className,
is = img.className.indexOf('open')>-1;
img.className = is?name.replace('-open',''):name+'-open';
}
}
}
})(document);
window.onload = function(){
var i = 0;
var data = [{id:i,name:'根节点',child:[]}];
while(i<100){
i++;
data[0].child.push({id:i,name:'节点'+i,child:[
{id:i*10+1,name:'节点'+i+'-1',child:[
{id:i*11+1,name:'节点'+i+'-1-2'},
{id:i*11+2,name:'节点'+i+'-1-3'},
{id:i*11+3,name:'节点'+i+'-1-4'}
]},
{id:i*10+2,name:'节点'+i+'-2',child:[
{id:i*11+4,name:'节点'+i+'-2-2'},
{id:i*11+5,name:'节点'+i+'-2-3'},
{id:i*11+6,name:'节点'+i+'-2-4'}
]},
{id:i*10+3,name:'节点'+i+'1-3'}
]});
}
var t = new Date().getTime();
new easyTree({
container : $$('demo'),
data : data
});

$$('sss').innerHTML ='一共1000个节点 共耗时:'+ (new Date().getTime()-t)+'毫秒'

}

</script>