Client Side Expand/Collapse All Nodes For ASP.NET 2.0 Treeview

本文介绍了一种使用 JavaScript 实现 ASP.NET TreeView 控件的全部展开或收缩功能的方法,无需服务器交互。通过修改元素显示状态实现,提供实用脚本及调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The asp.net treeview provieds a lot of features/functions, one of which is the Expand/Collapse All functionality on the server side. The Treeview Control has got two function for doing just that:
TreeView.ExpandAll(), TreeView.CollapseAll(). But going to server to accomplish such a simple functionality seemed a little odd to me. So, I wrote some javascript to do the same on the client.
Checkout the below script:

function TreeviewExpandCollapseAll(treeViewId, expandAll)
{
var displayState = (expandAll == true ? “none” : “block”);
var treeView = document.getElementById(treeViewId);
if(treeView)
{
var treeLinks = treeView.getElementsByTagName(”a”);
var nodeCount = treeLinks.length;
var flag = true;for(i=0;i<nodeCount;i++)
{
if(treeLinks[i].firstChild.tagName)
{
if(treeLinks[i].firstChild.tagName.toLowerCase() == “img”)
{
var node = treeLinks[i];
var level = parseInt(treeLinks[i].id.substr(treeLinks[i].id.length - 1),10);
var childContainer = GetParentByTagName(”table”, node).nextSibling;if(flag)
{
if(childContainer.style.display == displayState)
{
TreeView_ToggleNode(eval(treeViewId +”_Data”),level,node,’r',childContainer);
}
flag = false;
}
else
{
if(childContainer.style.display == displayState)
TreeView_ToggleNode(eval(treeViewId +”_Data”),level,node,’l',childContainer);
}
}
}
}//for loop ends
}
}//utility function to get the container of an element by tagname
function GetParentByTagName(parentTagName, childElementObj)
{
var parent = childElementObj.parentNode;
while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
{
parent = parent.parentNode;
}
return parent;
}

Get Formatted Version Of Above Script

The above script could be used as:

<a href=”javascript:TreeviewExpandCollapseAll(’<%=TreeView1.ClientID%>’, true)”>Expand All</a>
<a href=”javascript:TreeviewExpandCollapseAll(’<%=TreeView1.ClientID%>’, false)”>Collapse All</a>
<asp:TreeView ID=”TreeView1″ …………………

That’s all there is to it.

Hope this is helpful.

pushp

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值