要做出可以無限展開的分類樹,關鍵不在前端,而在資料表怎麼設計。做法是把「樹的形狀」事先攤平存進每一列:每一筆分類除了自己的 ID 與父 ID,還額外記錄根 ID、深度、父路徑與子節點數。這樣一來,查子分類不必遞迴,排序也不必每次重算整棵樹。
ClassID:主鍵。ClassName:分類名稱。ParentID:父分類 ID,0 代表頂層。ParentPath:祖先路徑,例如 0,1,7,用逗號串起所有上層 ID。有了它,「某節點底下的所有後代」就變成一句 LIKE '0,1,7,%'。Depth:深度,頂層為 0。RootID:所屬樹的根 ID,同一棵樹共享,方便整棵一起排序。Child:直接子節點數量,>0 就代表可以展開。OrderID:同層排序號。FilePath:靜態頁輸出目錄(因為這個站採靜態生成,才多這一欄)。類別的屬性對應資料庫欄位,方法則是「檢查 + 執行」兩兩成對:FAddCheck / SAdd、FEditCheck / SEdit、FDeleteCheck / SDelete。檢查失敗時回傳 1 並把原因寫進 ErrorStr,呼叫端只要看回傳值就知道能不能往下走。
<%
' 資料庫欄位 = 類屬性;新增、刪除、修改、檢查 = 類方法
Class Cls_Leibie
Private nClassID, sClassName, nParentID, sParentPath
Private nDepth, nRootID, nChild, nOrderID, sFilePath
Private rs, sql, ErrorStr
Private Sub Class_Initialize()
ErrorStr = "" ' 初始化錯誤訊息為空
End Sub
Private Sub Class_Terminate() ' 銷毀類時關閉連線
If IsObject(Conn) Then
Conn.Close
Set Conn = Nothing
End If
End Sub
'---------- 屬性:其餘欄位皆為相同的 Let/Get 配對 ----------
Public Property Let ClassID(str) ' 主鍵
nClassID = str
Call ClassProperty() ' 設定 ID 時立刻讀出整列屬性
End Property
Public Property Let ClassName(str)
sClassName = str
End Property
Public Property Get ClassName
ClassName = sClassName
End Property
Public Property Let ParentID(str)
nParentID = str
End Property
Public Property Get ParentID
ParentID = nParentID
End Property
' ParentPath / Depth / RootID / Child / OrderID / FilePath 依此類推
'-----------------------------------------------------------
' 依 ClassID 讀出該列的所有欄位
Private Sub ClassProperty()
sql = "select * from ArticleClass where ClassID=" & nClassID
Set rs = Conn.Execute(sql)
If Not rs.Eof Then
sClassName = Trim(rs("ClassName"))
nParentID = Trim(rs("ParentID"))
sParentPath = Trim(rs("ParentPath"))
nDepth = Trim(rs("Depth"))
nRootID = Trim(rs("RootID"))
nChild = Trim(rs("Child"))
nOrderID = Trim(rs("OrderID"))
sFilePath = Trim(rs("FilePath"))
End If
Set rs = Nothing
End Sub
' 回傳 0 = 通過;回傳 1 = 有錯,原因寫在 ErrorStr
Public Function FAddCheck()
Dim temprs
FAddCheck = 0
If sClassName = "" Then
FAddCheck = 1
ErrorStr = "類名不能為空!"
Exit Function
End If
If nParentID = "" Then
FAddCheck = 1
ErrorStr = "父 id 不能為空!"
Exit Function
End If
If nParentID <> 0 Then
' 父分類必須存在
Set temprs = Conn.Execute("select ClassID From ArticleClass where ClassID=" & nParentID)
If temprs.Eof Then
FAddCheck = 1
ErrorStr = "所屬類別不存在或已經被刪除!"
Exit Function
End If
Set temprs = Nothing
End If
' 同一父分類下的名稱不可重複
sql = "select ClassID from ArticleClass where ClassName='" & sClassName & _
"' and ParentID=" & nParentID
Set rs = Conn.Execute(sql)
If Not rs.Eof Then
FAddCheck = 1
ErrorStr = "類名重複!"
Exit Function
End If
Set rs = Nothing
End Function
Public Sub SAdd()
Dim maxClassID, maxRootID, prevOrderID
' 新 ClassID = 目前最大 + 1
Set rs = Conn.Execute("select Max(ClassID) from ArticleClass")
maxClassID = rs(0)
If IsNull(maxClassID) Then maxClassID = 0
Set rs = Nothing
nClassID = maxClassID + 1
' 新 RootID = 目前最大 + 1(若掛在父分類下,稍後會被改成父的根)
Set rs = Conn.Execute("select max(rootid) From ArticleClass")
maxRootID = rs(0)
If IsNull(maxRootID) Then maxRootID = 0
nRootID = maxRootID + 1
' 讀父分類的 RootID / Depth / ParentPath / Child
Set rs = Conn.Execute("select RootID,Depth,ParentPath,Child,OrderID " & _
"From ArticleClass where ClassID=" & nParentID)
If Not rs.Eof Then
nRootID = Trim(rs("Rootid")) ' 與父同根
sParentPath = Trim(rs("ParentPath")) & "," & nParentID ' 路徑接上自己
If CLng(Trim(nParentID)) > 0 Then
nDepth = CLng(Trim(rs("Depth"))) + 1 ' 深度 = 父深度 + 1
Else
nDepth = 0
End If
If CLng(Trim(rs("Child"))) > 0 Then
' 取同層最後一個 OrderID
Set rsPrevOrderID = Conn.Execute("select Max(OrderID) From ArticleClass where ParentID=" & ParentID)
prevOrderID = rsPrevOrderID(0)
' 再取同父但更深層級的最大 OrderID,較大者才是真正要接的號
Set rsPrevOrderID = Conn.Execute("select Max(OrderID) From ArticleClass where ParentPath like '" & ParentPath & ",%'")
If Not (rsPrevOrderID.Bof And rsPrevOrderID.Eof) Then
If Not IsNull(rsPrevOrderID(0)) Then
If rsPrevOrderID(0) > prevOrderID Then prevOrderID = rsPrevOrderID(0)
End If
End If
Set rsPrevOrderID = Nothing
Else
prevOrderID = 0
sParentPath = "0"
nDepth = 0
End If
End If
Set rs = Nothing
nChild = 0
nOrderID = prevOrderID + 1
sql = "insert into ArticleClass (ClassID,ClassName,ParentID,ParentPath," & _
"Depth,RootID,Child,OrderID,FilePath) values (" & _
nClassID & ",'" & sClassName & "'," & nParentID & ",'" & _
sParentPath & "'," & nDepth & "," & nRootID & "," & _
nChild & "," & nOrderID & ",'" & sFilePath & "')"
Conn.Execute(sql)
If ParentID > 0 Then
' 父分類的子節點數 +1
Conn.Execute("update ArticleClass set child=child+1 where ClassID=" & nParentID)
' 同樹中排序在後者通通往後挪一格
If prevOrderID <> "" Then
Conn.Execute("update ArticleClass set OrderID=OrderID+1 " & _
"where rootid=" & nRootid & " and OrderID>" & prevOrderID & _
" and ClassID<>" & nClassID)
End If
End If
End Sub
Public Function FEditCheck()
' 檢查:ID 不可空、名稱不可空、父分類須存在、同層不可重名
' 與 FAddCheck 幾乎相同,差別是重名檢查要排除自己:
' where ClassName='...' and ClassID<>本ID and ParentID=...
End Function
Public Sub SEdit()
sql = "update ArticleClass set ClassName='" & sClassName & _
"',FilePath='" & sFilePath & "' where ClassID=" & nClassID
Conn.Execute(sql)
End Sub
Public Function FDeleteCheck()
FDeleteCheck = 0
If nClassID = "" Then
FDeleteCheck = 1
ErrorStr = "要刪除的類別 id 不能為空!"
Exit Function
End If
Set rs = Conn.Execute("select Child from ArticleClass where ClassID=" & nClassID)
If rs.Bof And rs.Eof Then
FDeleteCheck = 1
ErrorStr = "類別不存在或者已經被刪除!"
Exit Function
End If
If Trim(rs("Child")) > 0 Then
FDeleteCheck = 1
ErrorStr = "該類別含有子類別,請刪除其子類別後再進行刪除本類別的操作!"
Exit Function
End If
End Function
Public Sub SDelete()
If nDepth > 0 Then
' 父分類的子節點數 -1
Conn.Execute("update ArticleClass set child=child-1 where child>0 and ClassID=" & nParentID)
End If
Conn.Execute("delete from ArticleClass where ClassID=" & nClassID)
End Sub
Public Function FErrStr()
FErrStr = ErrorStr
End Function
End Class
%>
前端只負責三件事:切換展開/收合並換圖示、把參數傳給右邊框架、以及用 Ajax 向 child.asp 撈出下一層的 HTML。
var xmlHttp;
var currentID = 1; // 目前選中的分類,若此 ID 不存在會出錯
// 分類顯示主函數
// cid = 子分類所在層的 id,id = 分類 id,pid = [+]/[-] 圖示 id,fid = 分類圖示 id
function DivDisplay(cid, id, pid, fid) {
if (GetId(cid).style.display == '') {
// 收合
GetId(cid).style.display = 'none';
GetId(pid).src = 'images/closed.gif';
GetId(fid).src = 'images/folder.gif';
} else {
// 展開
GetId(cid).style.display = '';
GetId(pid).src = 'images/opened.gif';
GetId(fid).src = 'images/folderopen.gif';
// 還沒抓過才抓,抓到之後就不再重複請求
if (GetId(cid).innerHTML == '' || GetId(cid).innerHTML == '正在提交資料...') {
GetId(cid).innerHTML = '';
ShowChild(cid, id);
}
}
}
// 作用與上者相同,只是用在「同層最後一個」分類,圖示換成 last* 系列
function DivDisplay2(cid, id, pid, fid) {
if (GetId(cid).style.display == '') {
GetId(cid).style.display = 'none';
GetId(pid).src = 'images/lastclosed.gif';
GetId(fid).src = 'images/folder.gif';
} else {
GetId(cid).style.display = '';
GetId(pid).src = 'images/lastopen.gif';
GetId(fid).src = 'images/folderopen.gif';
if (GetId(cid).innerHTML == '' || GetId(cid).innerHTML == '正在提交資料...') {
GetId(cid).innerHTML = '';
ShowChild(cid, id);
}
}
}
// 新增分類:掛上單擊/雙擊事件並展開
function ClassAdd(id) {
if (GetId("p" + id).src.indexOf("last") > 0) {
if (!GetId("p" + id).onclick) {
GetId("p" + id).onclick = function () { DivDisplay2("c" + id, id, "p" + id, "f" + id); };
GetId("s" + id).ondblclick = function () { DivDisplay2("c" + id, id, "p" + id, "f" + id); };
GetId("p" + id).src = 'images/lastopen.gif';
}
} else {
if (!GetId("p" + id).onclick) {
GetId("p" + id).onclick = function () { DivDisplay("c" + id, id, "p" + id, "f" + id); };
GetId("s" + id).ondblclick = function () { DivDisplay("c" + id, id, "p" + id, "f" + id); };
GetId("p" + id).src = 'images/opened.gif';
}
}
GetId("c" + id).style.display = '';
ShowChild("c" + id, id);
}
// 修改分類名稱(所見即所得,雙擊直接改字)
function ClassEdit(id, classname) {
GetId("s" + id).innerHTML = classname;
}
// 刪除分類
function ClassDel(id) {
ShowChild("c" + id, id);
CurrentSelect(currentID, id);
BrowseRight(id);
}
// 只剩一個子分類時的刪除:圖示改成不可展開的樣子
function ClassDel1(id) {
GetId("p" + id).style.cursor = "cursor";
GetId("p" + id).onclick = function () {};
GetId("s" + id).ondblclick = function () {};
GetId("p" + id).src = (GetId("p" + id).src.indexOf("last") > 0)
? 'images/lastnochild.gif'
: 'images/nofollow2.gif';
ShowChild("c" + id, id);
CurrentSelect(currentID, id);
BrowseRight(id);
}
// 把選中的分類 id 丟到右邊的內容框架
function BrowseRight(id) {
CurrentSelect(currentID, id);
top.ContentFrame.location = "../ArticleMain.asp?ClassID=" + id;
}
// 切換選取樣式
function CurrentSelect(oldid, newid) {
currentID = newid;
document.getElementById("s" + oldid).style.backgroundColor = "white";
document.getElementById("s" + currentID).style.backgroundColor = "#C0C0E9";
}
function GetId(id) {
return document.getElementById(id);
}
function CreateXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlHttp = new XMLHttpRequest();
}
}
function ShowChild(cid, id) {
CreateXMLHttpRequest();
if (!xmlHttp) {
GetId(cid).innerHTML = '抱歉,您的瀏覽器不支援 XMLHttpRequest,請使用 IE6 以上版本!';
return;
}
xmlHttp.open('POST', 'child.asp', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState != 4) {
GetId(cid).innerHTML = "正在提交資料...";
return;
}
if (xmlHttp.status == 200) {
GetId(cid).innerHTML = xmlHttp.responseText;
} else {
GetId(cid).innerHTML = '出錯:' + xmlHttp.statusText;
}
};
xmlHttp.send('id=' + id);
}
優點是查詢非常快。因為 ParentPath、Depth、RootID、Child 都已攤平存在,無論是「列出某節點的所有後代」、「同一棵樹的排序」還是「這個節點能不能展開」,都是一句 SQL 搞定,不必在應用層遞迴。
代價是寫入變複雜了:新增時要維護父節點的 Child 計數、同樹的 OrderID 位移、ParentPath 字串拼接;一旦某個節點被搬移,整棵子樹的 RootID / Depth / ParentPath 都得重算。刪除時也必須先確認沒有子節點(或改成連帶刪除)。這些冗餘欄位本質上是用「寫入成本」換「讀取效能」,在分類數量不大、變動不頻繁的情境下相當划算。
sClassName 直接串進 '...' 裡,只要名稱含單引號就會出事,惡意輸入更嚴重。應改用參數化查詢(ADO Command 的 Parameters 集合),至少也要先過濾單引號並限制長度。src.indexOf("last")。這種字串比對很脆弱,圖檔改名就壞。用 class 或 data 屬性標記狀態會穩得多。<a href="javascript:" 與 onclick 綁事件不利於無障礙,改成真正的按鈕並加上 aria-expanded 標示展開狀態,螢幕閱讀器才能理解這是一棵樹。WITH RECURSIVE)省去冗餘欄位。