论坛首页 Web前端技术论坛

Javascript实现树结构,欢迎拍砖

浏览 1943 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-05-29   最后修改:2009-05-29
近日写一个文章检索系统,需要用到一个树来动态显示数据库中存储的文章类别,于是自己操刀用JS编写。虽然实现了预期功能,但代码结构和实现逻辑(或说设计思路)并不是很理想,希望各位能够给些建议,谢谢!

先看下效果:


从数据库获取文章类别的代码如下:
<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;
			}
		}
 	}
  • 大小: 9.7 KB
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics