根據我的項目實踐情況,主要是幾個關鍵點:
1:支持靜態的樹,即一次性將全部數據加載到客戶端。
2:異步樹,即一次只加載一級或若干級節點,子節點可以異步加載數據。
3:Checkbox樹(可能是靜態樹也可能是異步樹),用於選擇(如選擇組織機構,選擇數據字典項)等,最好是能夠支持節點級聯(這個是難點)
4:能夠承載大數據量,並性能表現優異
5:能夠在主流浏覽器中運行良好
那我要打造的TreeView就是為了實現這個5個主要指標的。
先來看下效果圖
上圖是中國行政區域的數據樹,總共得節點是3500+。
那麼我們要開工了;
1:第一個確定的節點Dom結構(即用什麼樣的HTML來構建節點)
JQuery.treeview的節點結構
Jquery.TreeView IE6 下 展開第三級即出現錯位
IE8下展開到第5級
而我采用的也是第二種方式,但是縮進采用了填空的方式,即縮進的位置用空白的圖片填充來避免Jquery.treeview的問題
我的樹節點結構
確定了節點的HTML我們就可以來寫CSS了。有了效果圖,有個節點結構接著就編寫CSS了
下面是CSS的完整代碼
代碼如下:
.ie .bbit-tree .bbit-tree-bwrap{
}
.bbit-tree ul,.bbit-tree li
{
list-style-type:none;
margin:0px;
padding:0px;
}
.bbit-tree-body
{
font-size:12px;
}
.bbit-tree-icon, .bbit-tree-ec-icon, .bbit-tree-node-cb,.bbit-tree-elbow-line, .bbit-tree-elbow, .bbit-tree-elbow-end, .bbit-tree-elbow-plus, .bbit-tree-elbow-minus, .bbit-tree-elbow-end-plus, .bbit-tree-elbow-end-minus{
border: 0 none;
height: 18px;
margin: 0;
padding: 0;
vertical-align: top;
width: 16px;
background-repeat: no-repeat;
}
.bbit-tree-node-cb
{
height:16px;
}
.bbit-tree-node-collapsed .bbit-tree-node-icon, .bbit-tree-node-expanded .bbit-tree-node-icon, .bbit-tree-node-leaf .bbit-tree-node-icon{
border: 0 none;
height: 18px;
margin: 0;
padding: 0;
vertical-align: top;
width: 16px;
background-position:center;
background-repeat: no-repeat;
}
.ie .bbit-tree-node-indent img, .ie .bbit-tree-node-icon, .ie .bbit-tree-ec-icon {
vertical-align:middle !important;
}
.bbit-tree-noicon .bbit-tree-node-icon{
width:0; height:0;
}
/* No line styles 沒有線的樣式 */
.bbit-tree-no-lines .bbit-tree-elbow{
background:transparent;
}
.bbit-tree-no-lines .bbit-tree-elbow-end{
background:transparent;
}
.bbit-tree-no-lines .bbit-tree-elbow-line{
background:transparent;
}
/* Arrows Vista系統樹的樣式只有箭頭*/
.bbit-tree-arrows .bbit-tree-elbow{
background:transparent;
}
.bbit-tree-arrows .bbit-tree-elbow-plus{
background:transparent no-repeat 0 0;
}
.bbit-tree-arrows .bbit-tree-elbow-minus{
background:transparent no-repeat -16px 0;
}
.bbit-tree-arrows .bbit-tree-elbow-end{
background:transparent;
}
.bbit-tree-arrows .bbit-tree-elbow-end-plus{
background:transparent no-repeat 0 0;
}
.bbit-tree-arrows .bbit-tree-elbow-end-minus{
background:transparent no-repeat -16px 0;
}
.bbit-tree-arrows .bbit-tree-elbow-line{
background:transparent;
}
.bbit-tree-arrows .bbit-tree-ec-over .bbit-tree-elbow-plus{
background-position:-32px 0;
}
.bbit-tree-arrows .bbit-tree-ec-over .bbit-tree-elbow-minus{
background-position:-48px 0;
}
.bbit-tree-arrows .bbit-tree-ec-over .bbit-tree-elbow-end-plus{
background-position:-32px 0;
}
.bbit-tree-arrows .bbit-tree-ec-over .bbit-tree-elbow-end-minus{
background-position:-48px 0;
}
.bbit-tree-elbow-plus, .bbit-tree-elbow-minus, .bbit-tree-elbow-end-plus, .bbit-tree-elbow-end-minus{
cursor:pointer;
}
.ie ul.bbit-tree-node-ct{
font-size:0;
line-height:0;
zoom:1;
}
.bbit-tree-node{
white-space: nowrap;
}
.bbit-tree-node-el {
line-height:18px;
cursor:default;
/* cursor:pointer;*/
}
.bbit-tree-node a{
text-decoration:none;
-khtml-user-select:none;
-moz-user-select:none;
-webkit-user-select:ignore;
-kthml-user-focus:normal;
-moz-user-focus:normal;
-moz-outline: 0 none;
outline:0 none;
}
.bbit-tree-node a span{
text-decoration:none;
padding:1px 3px 1px 2px;
}
.bbit-tree-node .bbit-tree-node-disabled .bbit-tree-node-icon{
-moz-opacity: 0.5;
opacity:.5;
filter: alpha(opacity=50);
}
.bbit-tree-node .bbit-tree-node-inline-icon{
background:transparent;
}
.bbit-tree-node a:hover{
text-decoration:none;
}
/* Fix for ie rootVisible:false issue,修正一個IEdebug */
.bbit-tree-root {
zoom:1;
}
/***********這裡是圖標了,可以在這裡替換哦*****************/
.bbit-tree-node-expanded .bbit-tree-node-icon{
background-image:url(images/tree/folder-open.gif);
}
.bbit-tree-node-leaf .bbit-tree-node-icon{
background-image:url(images/tree/leaf.gif);
}
.bbit-tree-node-collapsed .bbit-tree-node-icon{
background-image:url(images/tree/folder.gif);
}
.bbit-tree-node-loading .bbit-tree-node-icon{
background-image:url(images/tree/loading.gif) !important;
}
.bbit-tree-node .bbit-tree-node-inline-icon {
background-image: none;
}
.bbit-tree-node-loading a span{
font-style: italic;
color:#444444;
}
.bbit-tree-lines .bbit-tree-elbow{
background-image:url(images/tree/elbow.gif);
}
.bbit-tree-lines .bbit-tree-elbow-plus{
background-image:url(images/tree/elbow-plus.gif);
}
.bbit-tree-lines .bbit-tree-elbow-minus{
background-image:url(images/tree/elbow-minus.gif);
}
.bbit-tree-lines .bbit-tree-elbow-end{
background-image:url(images/tree/elbow-end.gif);
}
.bbit-tree-lines .bbit-tree-elbow-end-plus{
background-image:url(images/tree/elbow-end-plus.gif);
}
.bbit-tree-lines .bbit-tree-elbow-end-minus{
background-image:url(images/tree/elbow-end-minus.gif);
}
.bbit-tree-lines .bbit-tree-elbow-line{
background-image:url(images/tree/elbow-line.gif);
}
.bbit-tree-no-lines .bbit-tree-elbow-plus{
background-image:url(images/tree/elbow-plus-nl.gif);
}
.bbit-tree-no-lines .bbit-tree-elbow-minus{
background-image:url(images/tree/elbow-minus-nl.gif);
}
.bbit-tree-no-lines .bbit-tree-elbow-end-plus{
background-image:url(images/tree/elbow-end-plus-nl.gif);
}
.bbit-tree-no-lines .bbit-tree-elbow-end-minus{
background-image:url(images/tree/elbow-end-minus-nl.gif);
}
.bbit-tree-arrows .bbit-tree-elbow-plus{
background-image:url(images/tree/arrows.gif);
}
.bbit-tree-arrows .bbit-tree-elbow-minus{
background-image:url(images/tree/arrows.gif);
}
.bbit-tree-arrows .bbit-tree-elbow-end-plus{
background-image:url(images/tree/arrows.gif);
}
.bbit-tree-arrows .bbit-tree-elbow-end-minus{
background-image:url(images/tree/arrows.gif);
}
/*TreeNode 選中的Disabled的一些顏色,字體樣式*/
.bbit-tree-node{
color:#000;
font: normal 11px arial, tahoma, helvetica, sans-serif;
}
.bbit-tree-node a{
color:#000;
}
.bbit-tree-node a span{
color:#000;
}
.bbit-tree-node .bbit-tree-node-disabled a span{
color:gray !important;
}
.bbit-tree-node .bbit-tree-node-over {
background-color: #eee;
}
.bbit-tree-node .bbit-tree-selected {
background-color: #d9e8fb;
}
上面了樹的基本樣式外,定義了一個有+號帶line的樣式和+號不帶line的樣式
這就是那個+號帶line的樣式
css中所用到的所有圖片
2:確定數據結構
代碼如下:
var menudata = [{
id: "0.1",//唯一的ID即可
text: "Beyondbit UI Demo",
hasChildren: true,
isexpand: true,
complete: true,
ChildNodes: [{
id: "0.1.1",
text: "日期選擇",
hasChildren: true,
isexpand: false,
complete: true,
ChildNodes: [{
id: "0.1.1.1",
text: "控件演示",
value: "Testpages/datepickerDemo.htm",
hasChildren: false,
isexpand: false,
complete: true,
ChildNodes: null
},
...
]
這樣的結構有個好處就數據本身是帶層次的,非常利於遍歷,在後面的級聯關聯中會看到
3: 面子做好了那就開始做裡子了,編寫腳本(Javascript)
我是JQuery得擁護者,所以自然js的框架自然是采用Jquery了
先上個完整代碼,再逐一分析
代碼如下:
/****************************************
author:xuanye.wan@gmail.com
page:http://xuanye.cnblogs.com/
***************************************/
(function($) {
$.fn.swapClass = function(c1, c2) {
return this.removeClass(c1).addClass(c2);
}
$.fn.switchClass = function(c1, c2) {
if (this.hasClass(c1)) {
return this.swapClass(c1, c2);
}
else {
return this.swapClass(c2, c1);
}
}
$.fn.treeview = function(settings) {
var dfop =
{
method: "POST",
datatype: "json",
url: false,
cbiconpath: "/images/icons/",
icons: ["checkbox_0.gif", "checkbox_1.gif", "checkbox_2.gif"],
showcheck: false, //是否顯示選擇
oncheckboxclick: false, //當checkstate狀態變化時所觸發的事件,但是不會觸發因級聯選擇而引起的變化
onnodeclick: false,
cascadecheck: true,
data: null,
clicktoggle: true, //點擊節點展開和收縮子節點
theme: "bbit-tree-arrows" //bbit-tree-lines ,bbit-tree-no-lines,bbit-tree-arrows
}
$.extend(dfop, settings);
var treenodes = dfop.data;
var me = $(this);
var id = me.attr("id");
if (id == null || id == "") {
id = "bbtree" + new Date().getTime();
me.attr("id", id);
}
var html = [];
buildtree(dfop.data, html);
me.addClass("bbit-tree").html(html.join(""));
InitEvent(me);
html = null;
//預加載圖片
if (dfop.showcheck) {
for (var i = 0; i < 3; i++) {
var im = new Image(16,16);
im.src = dfop.cbiconpath + dfop.icons[i];
}
}
//region
function buildtree(data, ht) {
ht.push("<div class='bbit-tree-bwrap'>"); // Wrap ;
ht.push("<div class='bbit-tree-body'>"); // body ;
ht.push("<ul class='bbit-tree-root ", dfop.theme, "'>"); //root
var l = data.length;
for (var i = 0; i < l; i++) {
buildnode(data[i], ht, 0, i, i == l - 1);
}
ht.push("</ul>"); // root and;
ht.push("</div>"); // body end;
ht.push("</div>"); // Wrap end;
}
//endregion
function buildnode(nd, ht, deep, path, isend) {
ht.push("<li class='bbit-tree-node'>");
ht.push("<div id='", id, "_", nd.id, "' tpath='", path, "' unselectable='on'");
var cs = [];
cs.push("bbit-tree-node-el");
if (nd.hasChildren) {
cs.push(nd.isexpand ? "bbit-tree-node-expanded" : "bbit-tree-node-collapsed");
}
else {
cs.push("bbit-tree-node-leaf");
}
if (nd.classes) { cs.push(nd.classes); }
ht.push(" class='", cs.join(" "), "'>");
//span indent
ht.push("<span class='bbit-tree-node-indent'>");
if (deep == 1) {
ht.push("<img class='bbit-tree-icon' src='../Themes/Shared/images/s.gif'/>");
}
else if (deep > 1) {
ht.push("<img class='bbit-tree-icon' src='../Themes/Shared/images/s.gif'/>");
for (var j = 1; j < deep; j++) {
ht.push("<img class='bbit-tree-elbow-line' src='../Themes/Shared/images/s.gif'/>");
}
}
ht.push("</span>");
//img
cs.length = 0;
if (nd.hasChildren) {
if (nd.isexpand) {
cs.push(isend ? "bbit-tree-elbow-end-minus" : "bbit-tree-elbow-minus");
}
else {
cs.push(isend ? "bbit-tree-elbow-end-plus" : "bbit-tree-elbow-plus");
}
}
else {
cs.push(isend ? "bbit-tree-elbow-end" : "bbit-tree-elbow");
}
ht.push("<img class='bbit-tree-ec-icon ", cs.join(" "), "' src='../Themes/Shared/images/s.gif'/>");
ht.push("<img class='bbit-tree-node-icon' src='../Themes/Shared/images/s.gif'/>");
//checkbox
if (dfop.showcheck && nd.showcheck) {
if (nd.checkstate == null || nd.checkstate == undefined) {
nd.checkstate = 0;
}
ht.push("<img id='", id, "_", nd.id, "_cb' class='bbit-tree-node-cb' src='", dfop.cbiconpath, dfop.icons[nd.checkstate], "'/>");
}
//a
ht.push("<a hideFocus class='bbit-tree-node-anchor' tabIndex=1 href='javascript:void(0);'>");
ht.push("<span unselectable='on'>", nd.text, "</span>");
ht.push("</a>");
ht.push("</div>");
//Child
if (nd.hasChildren) {
if (nd.isexpand) {
ht.push("<ul class='bbit-tree-node-ct' style='z-index: 0; position: static; visibility: visible; top: auto; left: auto;'>");
if (nd.ChildNodes) {
var l = nd.ChildNodes.length;
for (var k = 0; k < l; k++) {
nd.ChildNodes[k].parent = nd;
buildnode(nd.ChildNodes[k], ht, deep + 1, path + "." + k, k == l - 1);
}
}
ht.push("</ul>");
}
else {
ht.push("<ul style='display:none;'></ul>");
}
}
ht.push("</li>");
nd.render = true;
}
function getItem(path) {
var ap = path.split(".");
var t = treenodes;
for (var i = 0; i < ap.length; i++) {
if (i == 0) {
t = t[ap[i]];
}
else {
t = t.ChildNodes[ap[i]];
}
}
return t;
}
function check(item, state, type) {
var pstate = item.checkstate;
if (type == 1) {
item.checkstate = state;
}
else {// 上溯
var cs = item.ChildNodes;
var l = cs.length;
var ch = true;
for (var i = 0; i < l; i++) {
if ((state == 1 && cs[i].checkstate != 1) || state == 0 && cs[i].checkstate != 0) {
ch = false;
break;
}
}
if (ch) {
item.checkstate = state;
}
else {
item.checkstate = 2;
}
}
//change show
if (item.render && pstate != item.checkstate) {
var et = $("#" + id + "_" + item.id + "_cb");
if (et.length == 1) {
et.attr("src", dfop.cbiconpath + dfop.icons[item.checkstate]);
}
}
}
//遍歷子節點
function cascade(fn, item, args) {
if (fn(item, args, 1) != false) {
if (item.ChildNodes != null && item.ChildNodes.length > 0) {
var cs = item.ChildNodes;
for (var i = 0, len = cs.length; i < len; i++) {
cascade(fn, cs[i], args);
}
}
}
}
//冒泡的祖先
function bubble(fn, item, args) {
var p = item.parent;
while (p) {
if (fn(p, args, 0) === false) {
break;
}
p = p.parent;
}
}
function nodeclick(e) {
var path = $(this).attr("tpath");
var et = e.target || e.srcElement;
var item = getItem(path);
//debugger;
if (et.tagName == "IMG") {
// +號需要展開
if ($(et).hasClass("bbit-tree-elbow-plus") || $(et).hasClass("bbit-tree-elbow-end-plus")) {
var ul = $(this).next(); //"bbit-tree-node-ct"
if (ul.hasClass("bbit-tree-node-ct")) {
ul.show();
}
else {
var deep = path.split(".").length;
if (item.complete) {
item.ChildNodes != null && asnybuild(item.ChildNodes, deep, path, ul, item);
}
else {
$(this).addClass("bbit-tree-node-loading");
asnyloadc(ul, item, function(data) {
item.complete = true;
item.ChildNodes = data;
asnybuild(data, deep, path, ul, item);
});
}
}
if ($(et).hasClass("bbit-tree-elbow-plus")) {
$(et).swapClass("bbit-tree-elbow-plus", "bbit-tree-elbow-minus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-plus", "bbit-tree-elbow-end-minus");
}
$(this).swapClass("bbit-tree-node-collapsed", "bbit-tree-node-expanded");
}
else if ($(et).hasClass("bbit-tree-elbow-minus") || $(et).hasClass("bbit-tree-elbow-end-minus")) { //- 號需要收縮
$(this).next().hide();
if ($(et).hasClass("bbit-tree-elbow-minus")) {
$(et).swapClass("bbit-tree-elbow-minus", "bbit-tree-elbow-plus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-minus", "bbit-tree-elbow-end-plus");
}
$(this).swapClass("bbit-tree-node-expanded", "bbit-tree-node-collapsed");
}
else if ($(et).hasClass("bbit-tree-node-cb")) // 點擊了Checkbox
{
var s = item.checkstate != 1 ? 1 : 0;
var r = true;
if (dfop.oncheckboxclick) {
r = dfop.oncheckboxclick.call(et, item, s);
}
if (r != false) {
if (dfop.cascadecheck) {
//遍歷
cascade(check, item, s);
//上溯
bubble(check, item, s);
}
else {
check(item, s, 1);
}
}
}
}
else {
if (dfop.citem) {
$("#" + id + "_" + dfop.citem.id).removeClass("bbit-tree-selected");
}
dfop.citem = item;
$(this).addClass("bbit-tree-selected");
if (dfop.onnodeclick) {
dfop.onnodeclick.call(this, item);
}
}
}
function asnybuild(nodes, deep, path, ul, pnode) {
var l = nodes.length;
if (l > 0) {
var ht = [];
for (var i = 0; i < l; i++) {
nodes[i].parent = pnode;
buildnode(nodes[i], ht, deep, path + "." + i, i == l - 1);
}
ul.html(ht.join(""));
ht = null;
InitEvent(ul);
}
ul.addClass("bbit-tree-node-ct").css({ "z-index": 0, position: "static", visibility: "visible", top: "auto", left: "auto", display: "" });
ul.prev().removeClass("bbit-tree-node-loading");
}
function asnyloadc(pul, pnode, callback) {
if (dfop.url) {
var param = builparam(pnode);
$.ajax({
type: dfop.method,
url: dfop.url,
data: param,
dataType: dfop.datatype,
success: callback,
error: function(e) { alert("error occur!"); }
});
}
}
function builparam(node) {
var p = [{ name: "id", value: encodeURIComponent(node.id) }
, { name: "text", value: encodeURIComponent(node.text) }
, { name: "value", value: encodeURIComponent(node.value) }
, { name: "checkstate", value: node.checkstate}];
return p;
}
function InitEvent(parent) {
var nodes = $("li.bbit-tree-node>div", parent);
nodes.each(function(e) {
$(this).hover(function() {
$(this).addClass("bbit-tree-node-over");
}, function() {
$(this).removeClass("bbit-tree-node-over");
})
.click(nodeclick)
.find("img.bbit-tree-ec-icon").each(function(e) {
if (!$(this).hasClass("bbit-tree-elbow")) {
$(this).hover(function() {
$(this).parent().addClass("bbit-tree-ec-over");
}, function() {
$(this).parent().removeClass("bbit-tree-ec-over");
});
}
});
});
}
function getck(items, c, fn) {
for (var i = 0, l = items.length; i < l; i++) {
items[i].checkstate == 1 && c.push(fn(items[i]));
if (items[i].ChildNodes != null && items[i].ChildNodes.length > 0) {
getck(items[i].ChildNodes, c, fn);
}
}
}
me[0].t = {
getSelectedNodes: function() {
var s = [];
getck(treenodes, s, function(item) { return item });
return s;
},
getSelectedValues: function() {
var s = [];
getck(treenodes, s, function(item) { return item.value });
return s;
},
getCurrentItem: function() {
return dfop.citem;
}
};
return me;
}
//獲取所有選中的節點的Value數組
$.fn.getTSVs = function() {
if (this[0].t) {
return this[0].t.getSelectedValues();
}
return null;
}
//獲取所有選中的節點的Item數組
$.fn.getTSNs = function() {
if (this[0].t) {
return this[0].t.getSelectedNodes();
}
return null;
}
$.fn.getTCT = function() {
if (this[0].t) {
return this[0].t.getCurrentItem();
}
return null;
}
})(jQuery);
第一步:自然是所有Jquery的控件的第一步都是搭這個架子,兼容JQuery和$避免閉包,避免和其他類庫沖突,接受一個參數(是個對象)
代碼如下:
;(function($) {
//也可以使用$.fn.extend(treeview:function(setting){})
$.fn.treeview = function(settings) {
}
})(jQuery);
那第二步:給控件加一些參數默認參數,同時能調用方法$.extend讓最終調用時的參數覆蓋默認的(如果沒有則使用默認)
代碼如下:
var dfop ={
method: "POST",//默認采用POST提交數據
datatype: "json",//數據類型是json
url: false,//異步請求的url
cbiconpath: "/images/icons/",//checkbox icon的目錄位置
icons: ["checkbox_0.gif", "checkbox_1.gif", "checkbox_2.gif"],//checkbxo三態的圖片
showcheck: false, //是否顯示checkbox
oncheckboxclick: false, //點擊checkbox時觸發的事件
onnodeclick: false,//點擊node觸發的時間
cascadecheck: true,//是否啟用級聯
data: null,//初始化數據
theme: "bbit-tree-arrows" //三種風格備選bbit-tree-lines ,bbit-tree-no-lines,bbit-tree-arrows
}
//用傳進來的參數覆蓋默認,沒傳則保留
$.extend(dfop, settings);
第三步:生成默認數據的HTML(根據我們的分析節點的Dom結構,數據的數據結構,生成節點那是非常的簡單),,添加到當前容器中。最後是注冊事件這裡有一個非常重要的地方,即懶加載(沒有展開的節點HTML是不生成的),這就要求我們在樹內部要維護一套數據(開銷很小),對於性能的提升那是相當的明顯。另外一個重要的地方,就是使用一次生成所有展開節點的HTML並通過innerHTML屬性來生成Dom,而不是通過append操作,因為直接操作innerHTML比通過dom原生的方法要快上N倍(節點越多,N越大),切記切記!
代碼如下:
var treenodes = dfop.data; //內部的數據,其實直接用 dfop.data也可以
var me = $(this);
var id = me.attr("id");
if (id == null || id == "") {
id = "bbtree" + new Date().getTime();
me.attr("id", id);
}//全局唯一的ID
var html = [];
buildtree(dfop.data, html);//生成展開節點的HTML,push到數組中
me.addClass("bbit-tree").html(html.join(""));
InitEvent(me);//初始化事件
html = null;
在節點生成過程中,同時可生產節點的Path(節點路徑),方便檢索
代碼如下:
if (nd.hasChildren) { //存在子節點
if (nd.isexpand) {//同時節點已經展開則輸出子節點
ht.push("<ul class='bbit-tree-node-ct' style='z-index: 0; position: static; visibility: visible; top: auto; left: auto;'>");
if (nd.ChildNodes) {
var l = nd.ChildNodes.length;
for (var k = 0; k < l; k++) {//遞歸調用並生產節點的路徑
nd.ChildNodes[k].parent = nd;
buildnode(nd.ChildNodes[k], ht, deep + 1, path + "." + k, k == l - 1);
}
}
ht.push("</ul>");
}
else { //否則是待輸出狀態
ht.push("<ul style='display:none;'></ul>");
}
}
注冊事件,接受參數parent,即從某一父節點開始附加事件(因為做了個hover效果,所以事件是在每個節點上,如果取消該效果,事件可直接附加Tree上通過Event的srcElement來分發可略提升性能)
代碼如下:
function InitEvent(parent) {
var nodes = $("li.bbit-tree-node>div", parent);
nodes.each(function(e) {
$(this).hover(function() {
$(this).addClass("bbit-tree-node-over"); //鼠標浮動節點的樣式變化
}, function() {
$(this).removeClass("bbit-tree-node-over");
})
.click(nodeclick)//node的onclick事件,這個是重點哦
.find("img.bbit-tree-ec-icon").each(function(e) { //arrow的hover事件,為了實現vista那個風格的
if (!$(this).hasClass("bbit-tree-elbow")) {
$(this).hover(function() {
$(this).parent().addClass("bbit-tree-ec-over");
}, function() {
$(this).parent().removeClass("bbit-tree-ec-over");
});
}
});
});
}
這裡最主要的還是node的click事件,因為他要處理的事情很多,如樹的展開收縮(如果子節點不存在,但是hasChildren為真,同時complete屬性不為真則需要異步加載子節點,如子節點存在,但是沒有Render那麼就要Render),點擊checkbox要出發級聯的事件和oncheckbox事件,點擊其他則觸發配置條件的nodeonclick事件,這一切都通過前面event的源元素的class來區分點擊的對象
代碼如下:
function nodeclick(e) {
var path = $(this).attr("tpath");//獲取節點路徑
var et = e.target || e.srcElement;//獲取事件源
var item = getItem(path);//根據path獲取節點的數據
//debugger;
if (et.tagName == "IMG") {
// +號需要展開,處理加減號
if ($(et).hasClass("bbit-tree-elbow-plus") || $(et).hasClass("bbit-tree-elbow-end-plus")) {
var ul = $(this).next(); //"bbit-tree-node-ct"
if (ul.hasClass("bbit-tree-node-ct")) {
ul.show();
}
else {
var deep = path.split(".").length;
if (item.complete) {
item.ChildNodes != null && asnybuild(item.ChildNodes, deep, path, ul, item);
}
else {
$(this).addClass("bbit-tree-node-loading");
asnyloadc(ul, item, function(data) {
item.complete = true;
item.ChildNodes = data;
asnybuild(data, deep, path, ul, item);
});
}
}
if ($(et).hasClass("bbit-tree-elbow-plus")) {
$(et).swapClass("bbit-tree-elbow-plus", "bbit-tree-elbow-minus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-plus", "bbit-tree-elbow-end-minus");
}
$(this).swapClass("bbit-tree-node-collapsed", "bbit-tree-node-expanded");
}
else if ($(et).hasClass("bbit-tree-elbow-minus") || $(et).hasClass("bbit-tree-elbow-end-minus")) { //- 號需要收縮
$(this).next().hide();
if ($(et).hasClass("bbit-tree-elbow-minus")) {
$(et).swapClass("bbit-tree-elbow-minus", "bbit-tree-elbow-plus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-minus", "bbit-tree-elbow-end-plus");
}
$(this).swapClass("bbit-tree-node-expanded", "bbit-tree-node-collapsed");
}
else if ($(et).hasClass("bbit-tree-node-cb")) // 點擊了Checkbox
{
var s = item.checkstate != 1 ? 1 : 0;
var r = true;
if (dfop.oncheckboxclick) { //觸發配置的函數
r = dfop.oncheckboxclick.call(et, item, s);
}
if (r != false) {//如果返回值不為false,即checkbxo變化有效
if (dfop.cascadecheck) {//允許觸發級聯
//遍歷
cascade(check, item, s);//則向下關聯
//上溯
bubble(check, item, s); //向上關聯
}
else {
check(item, s, 1);//否則只管自己
}
}
}
}
else {//點擊到了其他地方
if (dfop.citem) { //上一個當前節點
$("#" + id + "_" + dfop.citem.id).removeClass("bbit-tree-selected");
}
dfop.citem = item;//這次的當前節點
$(this).addClass("bbit-tree-selected");
if (dfop.onnodeclick) {
dfop.onnodeclick.call(this, item);
}
}
}
展開節點,異步請求的部分代碼應該不是很復雜就不細訴了,關鍵來講一下級聯
級聯有兩個問題要處理,第一個是遍歷子節點,第二個是上溯到祖節點,因為我們的數據結構這兩個操作都顯得非常簡單
代碼如下:
//遍歷子節點
function cascade(fn, item, args) {
if (fn(item, args, 1) != false) {
if (item.ChildNodes != null && item.ChildNodes.length > 0) {
var cs = item.ChildNodes;
for (var i = 0, len = cs.length; i < len; i++) {
cascade(fn, cs[i], args);
}
}
}
}
//冒泡的祖先
function bubble(fn, item, args) {
var p = item.parent;
while (p) {
if (fn(p, args, 0) === false) {
break;
}
p = p.parent;
}
}
找到節點的同時都會觸發check這個回調函數,來判斷當前節點的狀態,詳細請看下面代碼中的注釋部分應該是比較清晰,描寫了這個過程
代碼如下:
function check(item, state, type) {
var pstate = item.checkstate; //當前狀態
if (type == 1) {
item.checkstate = state; //如果是遍歷子節點,父是什麼子就是什麼
}
else {// 上溯 ,這個就復雜一些了
var cs = item.ChildNodes; //獲取當前節點的所有子節點
var l = cs.length;
var ch = true; //是否不是中間狀態 半選
for (var i = 0; i < l; i++) {
if ((state == 1 && cs[i].checkstate != 1) || state == 0 && cs[i].checkstate != 0) {
ch = false;
break;//他的子節點只要有一個沒選中,那麼他就是半選
}
}
if (ch) {
item.checkstate = state;//不是半選,則子節點是什麼他就是什麼
}
else {
item.checkstate = 2; //半選
}
}
//change show 如果節點已輸出,而其前後狀態不一樣,則變化checkbxo的顯示
if (item.render && pstate != item.checkstate) {
var et = $("#" + id + "_" + item.id + "_cb");
if (et.length == 1) {
et.attr("src", dfop.cbiconpath + dfop.icons[item.checkstate]);
}
}
}
至此我們樹的主體功能已經完全實現了。其他就是公開一些方法等,大家可詳見代碼,示例中公開了兩個一個當前選中的所有節點,另外一個當前的節點。
大家可以通過以下網址查看文中的示例,selected拼錯了,大家海涵! windows azure部署還是麻煩懶得修改了3500+節點一次加載,大家可以點擊根節點的全選來看看速度
http://jscs.cloudapp.net/ControlsSample/BigTreeSample
異步加載,按需加載的情況也是非常常用的,使用的是SQL Azure服務器在美國ing,所以可能異步有點慢,本地數據源那是瞬間的
http://jscs.cloudapp.net/ControlsSample/TreeAsnySample
FAQ:
1:如何設置每個節點不同的圖標?
回答:
其實不用擴展,本身就支持,只是沒有說明而已,我們來看一下這個代碼吧?在BuildNode方法中有這麼一句?
if (nd.classes) { cs.push(nd.classes); }
在節點的數據結構中可以設置屬性classes ,該屬性將作為節點特殊的Css Class 添加到節點上。那麼利用這點,就可以設置節點的圖標了
然後就是編寫一個Style 即可
最後來看下效果吧?