近日写一个文章检索系统,需要用到一个树来动态显示数据库中存储的文章类别,于是自己操刀用JS编写。虽然实现了预期功能,但代码结构和实现逻辑(或说设计思路)并不是很理想,希望各位能够给些建议,谢谢!
先看下效果:
[img]/upload/attachment/109088/e0d9d292-292a-3573-81fc-9f33da1fabaa.jpg[/img]
从数据库获取文章类别的代码如下:
控制树展开和收缩动作的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;
}
}
}