Javascript实现树结构,欢迎拍砖

近日写一个文章检索系统,需要用到一个树来动态显示数据库中存储的文章类别,于是自己操刀用JS编写。虽然实现了预期功能,但代码结构和实现逻辑(或说设计思路)并不是很理想,希望各位能够给些建议,谢谢!

先看下效果:
[img]/upload/attachment/109088/e0d9d292-292a-3573-81fc-9f33da1fabaa.jpg[/img]

从数据库获取文章类别的代码如下:

<dl class="nav3-grid">
<%
CategoryDao dao = (CategoryDao)DaoConfig.getDaoManager().getDao(CategoryDao.class);
List<Category> categoryList = dao.getAll();
if(categoryList != null && categoryList.size() != 0){
for(Category category : categoryList){//The first tier
if(category.getParentId() == 0){
%><dt><a href="#" onclick="displayChildren(this)"><%=category.getCategoryName() %></a></dt><%
List<Category> children = dao.getChildren(category.getCategoryId());
if(children != null && children.size() != 0){
for(Category child : children){//The second tier
%><dd style="display:none"><a href="#" onclick="displayChildren(this)"><%=child.getCategoryName() %></a></dd><%
List<Category> grandson = dao.getChildren(child.getCategoryId());
if(grandson != null && grandson.size() != 0){
for(Category cate : grandson){//The third tier
%><dd class="third" style="display:none"><a href="getPapersByCategory.action?id=<%=cate.getCategoryId() %>"><%=cate.getCategoryName() %></a></dd><%
}
}
}
}
}
}
}
%>
</dl>


控制树展开和收缩动作的JS代码:

function displayChildren(category){
var tag = category.parentNode.tagName;
if(tag == 'DT'){//when click the first tier
var nextNode = category.parentNode.nextSibling;
while(nextNode.nodeName == 'DD' && nextNode.className == ''){
if(nextNode.style.display == 'block'){
nextNode.style.display = 'none';
var nextSibl = nextNode.nextSibling;
while(nextSibl.className == 'third'){
nextSibl.style.display = 'none';
nextSibl = nextSibl.nextSibling;
}
}
else nextNode.style.display = 'block';
nextNode = nextNode.nextSibling;
}
}else if(tag == 'DD'){//when click the second tier
var nextNodeDD = category.parentNode.nextSibling;
while((nextNodeDD.nodeName == 'DD') && (nextNodeDD.className == 'third')){
if(nextNodeDD.style.display == 'block')
nextNodeDD.style.display = 'none';
else nextNodeDD.style.display = 'block';
nextNodeDD = nextNodeDD.nextSibling;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值