該例子演示了無(wú)限級(jí)分類的顯示和添加.只用一個(gè)數(shù)據(jù)表實(shí)現(xiàn)記錄無(wú)限級(jí)分類,關(guān)鍵是每條記錄都記錄了上一層類別的id(parentid),然后通過(guò)一個(gè)遞歸函數(shù)來(lái)不斷將類別顯示出來(lái).
*大類1
└二級(jí)小類1
└三級(jí)小類1
└四級(jí)小類1
└五級(jí)小類1
*大類2
└二級(jí)小類2
*大類3
數(shù)據(jù)庫(kù)說(shuō)明:數(shù)據(jù)庫(kù)db.mdb,classtable表的結(jié)構(gòu):classid類別id(自動(dòng)增長(zhǎng)) parentid 父級(jí)id 默認(rèn)為0 (0代表最高級(jí)) classname類別名,classdepth是為了記錄類別的級(jí)數(shù) ———————————————-
| classid| classname| parentid | classdepth |
———————————————-
主要代碼:
//先取出最高級(jí)(parentid=0)的分類
<%
set conn=server.createobject("adodb.connection")
conn.open "provider=microsoft.jet.oledb.4.0;data source="&server.mappath("db.mdb")
set rs1=server.createobject("adodb.recordset")
sql1="select * from classtable where parentid=0 order by classid"
rs1.open sql1,conn,1,1
if rs1.eof or rs1.bof then
response.write"還沒(méi)分類!"
else
while not rs1.eof
id1=rs1("classid")
name1=rs1("classname")
response.write "*"&name1&"
"
parentid1=rs1("parentid")
call reclass(id1)
rs1.movenext
wend
end if
rs1.close
set rs1=nothing
sub reclass(id)
'遞歸調(diào)用函數(shù),生成一個(gè)類別代碼
set rs=server.createobject("adodb.recordset")
sql="select * from classtable where parentid="&id
rs.open sql,conn,1,1
i=1
while not rs.eof
id0=rs("classid")
classname0=rs("classname")
parentid0=rs("parentid")
classdepth0=rs("classdepth")
brstr=""
for j=1 to classdepth0
brstr=" "&brstr
next
response.write(brstr&"└"&classname0&"
")
call reclass(id0)
rs.movenext
i=i+1
wend
rs.close
set rs=nothing
end sub
if request("a")="add" then
call add
end if
if request("name")<>"" then
%>
<%end if
sub add '添加類別
id=request("id")
classname=request("classname")
set rs=server.createobject("adodb.recordset")
rs.open "select parentid,classdepth from classtable where classid="&id,conn,1,1
parentid=rs(0)
classdepth=rs(1)+1
rs.close
set rs=nothing
sql="insert into classtable (classname,parentid,classdepth) values ('"&classname&"',"&id&","&classdepth&")"
conn.execute sql
response.write""
end sub
%>
該文章在 2010/7/13 22:13:16 編輯過(guò)