HTML树结构,XML TO TREE 树
我有些方案需要用到XML结构,比如说将无级分类生成XML,以便前台操作,不需要时时读取数据库. 以前写过 XML TO TREE,这种不利于搜索引擎优化,所以选了一方案,将XML转成HTML,再将HTML做成树.
先上图
HTML结构如下:
<dl>
<dt>内容</dt>
<dd>
子类,如此重复
</dd>
</dl>
Firebug 图
JS代码:
function Html2Tree(box, type) { this.panel = this.get(box); this.init(); if (type) { this.panel.className = 'Html2Tree Html2Tree_' + type; } }; Html2Tree.prototype = { init: function() { var nodes = this.tag('dl', this.panel), S = this; for (var i = nodes.length; i--; ) { var dl = nodes[i], dd = this.tag('dd', dl), dt = this.tag('dt', dl)[0]; this.setLast(dl); if (dd.length == 0) { dt.className = 'file'; } else if (S.display(dd[0]) != 'none') { dt.className = 'open'; } } this.live(function() { var dd = S.next(this), open; if (dd) { open = S.display(dd) == 'none' dd.style.display = open ? 'block' : 'none'; this.className = open ? 'open' : ''; } }, function() { return /dt/i.test(this.nodeName); }); }, display: function(el) { var cc = el.currentStyle || document.defaultView.getComputedStyle(el, null); return el.style['display'] || cc['display']; }, live: function(fn, c) { this.panel.onclick = function(e) { e = e || window.event; var s = e.srcElement || e.target; while (s && s !== this) { if (c.call(s)) { fn.call(s, e); break; } s = s.parentNode; } }; }, next: function(dt) { var next = dt, dd; do { next = next.nextSibling; if (next && /dd/i.test(next.nodeName)) { dd = next; break; } } while (next); return dd; }, setLast: function(dl) { var last = dl, next = dl; do { next = next.nextSibling; if (next && /dl/i.test(next.nodeName)) { last = next; } } while (next); last.className = 'last'; }, get: function(el) { return typeof el == "string" ? document.getElementById(el) : el; }, tag: function(tag, el) { return (el || document.body).getElementsByTagName(tag); } };
调用方法
new Html2Tree('tree', 'min'); //皮肤: red, xp, min, circle, a3, black, chm // 第二个参数为皮肤,共支持 7 种皮肤
最后就是代码打包下载哈哈,欢迎拍砖,请不要恶语相向,你可以选择用或者不用.!
感谢: 感谢果果提供部分代码!
原创代码,转载请联系 柴哥!!!