本来打算过些日子总结树的,看看最近几个网友发消息(邮件)问我相关树方面的问题,今天我没有休息,花了3个多小时总结我们在使用树中经常遇到的问题,好了下面就让我们来看看这些树吧!
第一棵:使用AJAX 按需求建立【一棵】树 Building Tree View on demand using AJAX
http://www.cnblogs.com/OceanChen/archive/2009/02/07/1385664.html
这篇文章简单告诉我们如何使用AJAX异步生成树,且数据源为XML,看看截图,是不是很酷?当然你还可以在链接上下载源代码!
文章出去: http://www.codeproject.com/KB/aspnet/TreeViewAjax.aspx
第二棵:用使用JavaScript展开/折叠TreeView中所有节点(Expand and Collapse All Nodes of asp.net Treeview on the client with javascript)
http://www.cnblogs.com/OceanChen/archive/2009/02/07/1385662.html
这是我给客户的一个解决方案,为了节约时间,我直接贴可以跑到代码,同时没有写注释,希望谅解,
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>TreeView Demo</title>
<script language="javascript" type="text/javascript">
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;
for (i = 0; i < nodeCount; i++) {
if (treeLinks[i].firstChild.tagName) {
if (treeLinks[i].firstChild.tagName.toLowerCase() == "img") {
var currentToggleLink = treeLinks[i];
var childContainer = GetParentByTagName("table", currentToggleLink).nextSibling;
if (childContainer.style.display == displayState) {
eval(currentToggleLink.href);
}
}
}
}
}
}
function GetParentByTagName(parentTagName, childElementObj) {
var parent = childElementObj.parentNode;
while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
parent = parent.parentNode;
}
return parent;
} </script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeViewDemo" runat="server" ExpandDepth="1">
<Nodes>
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A" Value="A">
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A1" Value="A1">
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A11" Value="A11"></asp:TreeNode>
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A12" Value="A12"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A2" Value="A2">
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A21" Value="A21"></asp:TreeNode>
<asp:TreeNode NavigateUrl="http://www.asp.net" Text="A22" Value="A22"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
<a href="javascript:TreeviewExpandCollapseAll('<%=TreeViewDemo.ClientID%>', true)">Expand
All</a> <a href="javascript:TreeviewExpandCollapseAll('<%=TreeViewDemo.ClientID%>', false)">
Collapse All</a>
</div>
</form>
</body>
</html>
刚刚从网上搜索我的文章时候,看到另外个文章和我写的差不多,故我也把那里的代码贴过来共大家参考:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jstree.aspx.cs" Inherits="jstree" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function expandAll(treeViewId)
{
var treeView = document.getElementById(treeViewId);
var treeLinks = treeView.getElementsByTagName("a");
var j = true;
for(i=0;i<treeLinks.length;i++)
{
if(treeLinks[i].firstChild.tagName == "IMG")
{
var node = treeLinks[i];
var level = parseInt(treeLinks[i].id.substr(treeLinks[i].id.length - 1),10);
var childContainer = document.getElementById(treeLinks[i].id + "Nodes");
if(j)
{
if(childContainer.style.display == "none")
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'r',childContainer);
j = false;
}
else
{
if(childContainer.style.display == "none")
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'l',childContainer);
}
}
}
}
function collapseAll(treeViewId)
{
var treeView = document.getElementById(treeViewId);
var treeLinks = treeView.getElementsByTagName("a");
var j = true;
for(i=0;i<treeLinks.length;i++)
{
if(treeLinks[i].firstChild.tagName == "IMG")
{
var node = treeLinks[i];
var level = parseInt(treeLinks[i].id.substr(treeLinks[i].id.length - 1),10);
var childContainer = document.getElementById(treeLinks[i].id + "Nodes");
if(j)
{
if(childContainer.style.display == "block")
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'r',childContainer);
j = false;
}
else
{
if(childContainer.style.display == "block")
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'l',childContainer);
}
}
}
}
function Button1_onclick() {
expandAll('<%=TreeView1.ClientID%>');
}
function Button2_onclick() {
collapseAll('<%=TreeView1.ClientID%>');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
<asp:TreeNode Text="New Node" Value="New Node">
<asp:TreeNode Text="New Node" Value="New Node"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
</form>
<p>
<input id="Button1" type="button" value="Expand All" onclick="return Button1_onclick()" /></p>
<p>
<input id="Button2" type="button" value="Collapse All" onclick="return Button2_onclick()" /></p>
</body>
</html>
这是第二段代码的出处:http://www.cnblogs.com/blodfox777/archive/2008/10/02/1303119.html
这个是我写文章出处:http://forums.asp.net/p/1355481/2779144.aspx
第三棵:Microsfot.Web.UI.WebControls.TreeView JavaScript控制方法研究
http://www.cnblogs.com/OceanChen/archive/2009/02/07/1385656.html
-
被选择的节点的索引:
tree.selectedNodeIndex -
被单击的节点的索引:
tree.clickedNodeIndex -
获取一个节点:
tree.getTreeNode(nodeIndex) -
在根节点下增加一个子节点:
var tree = document.all['TreeView1'];
var node = tree.createTreeNode() ;
tree.add(node);
node.setAttribute( "text", "aaaa"); -
在当前节点下增加一个子节点:
var tree = document.all['TreeView1'];
var node = tree.createTreeNode() ;
var parentNode = tree.getTreeNode( tree.clickedNodeIndex);
parentNode.add(node);
node.setAttribute( "text", "aaaa"); - 通过XML文件来增加子节点:
node.setAttribute("NavigateUrl","xxx");
node.databind(); - 动态增加子节点后自动展开:
node.setAttribute('expanded', 'true');//MS提供的HTC中需要修改一个地方,否则就会产生一个异常 - 获取节点的属性:
node.getAttribute("xxx") - 设置节点的属性 :
node.setAttribute('xxx', 'xxxx'); - 常用属性列表:
属性 值 含义 CheckBox True False 是否有选择框 checked True False 选择框是否被选中 Expanded True False 是否展开 ImageURL 正常状态下左边的图标 SelectedImageUrl 当节点被选择时左边的图标 ExpandedImageUrl 当节点被展开后左边的图标 Target 目标框架 navigateurl 目标URL type 节点的类型 childtype 子节点的类型 Text 节点显示的文本 innerText innerHTML defaultstyle 默认的风格 hoverstyle 当鼠标移到节点的上面时的风格 selectedstyle 当节点被选择时的风格 treenodesrc - 获取父节点:
node.getParent() - 获取子节点:
node.getChildren() - 判断节点是否有子节点
node.getChildren().length > 0 - 响应onselectedindexchange事件:
var tree = document.all["tvMain"];
tree.attachEvent("onselectedindexchange", SelectedIndexChange);
原文出处:http://www.cnblogs.com/caidaoli/archive/2005/02/23/108317.html
第四棵:在ASP.NET 2.0 中如何使用多个Sitemap文件【Using Multiple Sitemap Files in ASP.NET 2.0--英文】
http://www.cnblogs.com/OceanChen/archive/2009/02/06/1385200.html
请直接参考链接先:
http://www.codeproject.com/KB/aspnet/MutlipleSiteMap.aspx【英文的——有代码下载】
通过这个,我们就可以很容易给特定用户看特定的站点导航了。
参考部分代码:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ContractedBlock.gif)
如果再加上这篇,何愁网站人性化导航不破?
【原】根据网站动态目录生成树结构,并用TreeView输出【提供源码下载,有详细注释】
http://www.cnblogs.com/OceanChen/archive/2009/02/05/1384816.html
第五棵:根据网站动态目录生成树结构,并用TreeView输出【提供源码下载,有详细注释】
http://www.cnblogs.com/OceanChen/archive/2009/02/05/1384816.html
各位博友好,本着共享的原则,本人花了点时间写了个这棵树,虽然简单,但是应该很实用。
我知道我们可以使用 Web.sitemap 来实现,但是用Web.sitemap 需要预先写好配置,我写这个就不需要考虑配置了。
比如说你的目录改变了,那么自动生成树也会跟着变动,下面贴代码:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyWebsiteTreeView.aspx.cs"
Inherits="MyWebsiteTreeView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
<asp:DropDownList ID="ddlRootDirectory" runat="server">
</asp:DropDownList>
<asp:Button ID="btnGenerateDirectoryTree" runat="server" Text="Ggenerate Directory Tree"
onclick="btnGenerateDirectoryTree_Click" />
</div>
</form>
</body>
</html>
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class MyWebsiteTreeView : System.Web.UI.Page
{
/// <summary>
/// 页面加载时,就动态绑定目录到DropDownList控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDirectoryToDropDownList(ddlRootDirectory);
}
}
/// <summary>
/// 调整树节点,使与Firefox 浏览器兼容
/// </summary>
/// <param name="node"></param>
void SdjustNodes(TreeNode node)
{
string ab = node.NavigateUrl;
//Suodaosoft 是根目录名
node.NavigateUrl = node.NavigateUrl.Replace("Suodaosoft//", "");
node.NavigateUrl = node.NavigateUrl.Replace("//", "/");//与 Firefox 兼容,IE 能识别“//”,可是FireFox 不能识别
if (node.ChildNodes.Count > 0)
{
foreach (TreeNode childNode in node.ChildNodes)
{
SdjustNodes(childNode);
}
}
}
TreeNode OutputDirectory(System.IO.DirectoryInfo directory, TreeNode parentNode)
{
// 检验目录是否为空
if (directory == null) return null;
// 为目录建立节点
TreeNode DirNode = new TreeNode(directory.Name);
// 从当前目录得到子目录
System.IO.DirectoryInfo[] SubDirectories = directory.GetDirectories();
// 得出子目录
for (int DirectoryCount = 0; DirectoryCount < SubDirectories.Length; DirectoryCount++)
{
OutputDirectory(SubDirectories[DirectoryCount], DirNode);
}
// 输出当前目录文件
System.IO.FileInfo[] Files = directory.GetFiles();
for (int FileCount = 0; FileCount < Files.Length; FileCount++)
{
//------------------------------------
//注意,我注释了if 的条件!
//这儿其实有个小技巧
//可以筛选你想要的文件
//------------------------------------
//if (Files[FileCount].Extension == ".htm")
//{
string filename = ConvertFileToRelativePaths(Files[FileCount].FullName, "Suodaosoft");
DirNode.ChildNodes.Add(new TreeNode(Files[FileCount].Name, Files[FileCount].Name, "", filename, "_blank"));
//}
}
//如果父节点是NULL, 就返回本节点
//否则就加到父节点,并返回父节点
if (parentNode == null)
{
return DirNode;
}
else
{
parentNode.ChildNodes.Add(DirNode);
return parentNode;
}
}
/// <summary>
/// 转换文件路径
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="rootName">根目录名</param>
/// <returns>目录</returns>
string ConvertFileToRelativePaths(string fileName, string rootName)
{
return fileName.Substring(fileName.LastIndexOf(rootName));
}
/// <summary>
/// 建立目录树
/// </summary>
/// <param name="tv"></param>
void GenerateDirectoryTree(TreeView tv)
{
tv.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(Server.MapPath("~/" + ddlRootDirectory.SelectedValue + "/"));
if (ddlRootDirectory.SelectedValue == "Root")
{
RootDir = new System.IO.DirectoryInfo(Server.MapPath("~/"));
}
// 把目录树输出到一个节点
TreeNode RootNode = OutputDirectory(RootDir, null);
// 把目录树加入根节点
TreeView1.Nodes.Add(RootNode);
foreach (TreeNode node in tv.Nodes)
{
SdjustNodes(node);
}
}
/// <summary>
/// 把动态目录绑定到DropDownList控件上,供选择目录,如果选择Root,表示项Web工程的根节点
/// </summary>
/// <param name="ddl"></param>
void BindDirectoryToDropDownList(DropDownList ddl)
{
ddl.Items.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(Server.MapPath("~/"));//根节点
System.IO.DirectoryInfo[] SubDirectories = RootDir.GetDirectories();
ddl.Items.Add("Root");
foreach (DirectoryInfo dir in SubDirectories)
{
ddl.Items.Add(dir.Name);
}
}
/// <summary>
/// 根据DropDownList选择的目录,动态产生树
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnGenerateDirectoryTree_Click(object sender, EventArgs e)
{
GenerateDirectoryTree(TreeView1);
}
}
具体应用,请在下面的这个链接上下载整个应用项目示例:
http://www.cnblogs.com/OceanChen/archive/2009/02/04/1383794.html
第六棵:给TreeView 加个确认导航功能(如虎添翼?还是画蛇添足?)【可用代码,且有注释】
http://www.cnblogs.com/OceanChen/archive/2009/02/05/1384439.html
最近回答客户问题时,遇到这样的问题【人啊,想法就是多!】,说是要给TreeView 导航加个导航确认功能,开始看那个英文啊,好别扭!经过仔细问问,终于知道他到底要什么,然后自己就Google啊,可是不行,没有现成的,然后没有办法,我个人认为我的JS功底是一等一 Js还算可以【高人很多,不能放肆,谢谢高人指点】的,写个给他把,果然客户觉得爽,所以我觉得有必要公布出来供大家参考,本啦注释是E文的,我怕有些初学者不识E文,就修改注释为中文的了,发扬我一贯作风,贴可以跑起来的代码:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string confirmMessage = "是否要继续?Y/N?";
//定义客户端事件 treeNodeConfirmation
string script = @"function treeNodeConfirmation(MyEvent, text)
{
var obj;
// 检测是否是IE
if (MyEvent.srcElement)
{
obj = MyEvent.srcElement;
}
// 如果不是IE,则用其它(可能是NS 或 FF 等)
else if (MyEvent.target)
{
obj = MyEvent.target;
}
// 判断是否是LINK(tag A),因TreeView控件解析后是table + a 组合的,故要检测 A TAG
if(obj.tagName == 'A' || obj.tagName == 'a')
{
return confirm (text);
}
}";
//注册事件
ScriptManager.RegisterClientScriptBlock(myTreeView, typeof(TreeView), "treeNodeClickConfirm", script, true);
//事件写入TreeView 的属性中,即在单击TreeView控件时调用事件
myTreeView.Attributes.Add("onclick", "javascript:return treeNodeConfirmation(event, '" + confirmMessage + "')");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="myTreeView" runat="server" >
<Nodes>
<asp:TreeNode Text="My Computer">
<asp:TreeNode Text="Favorites">
<asp:TreeNode Text="News">
<asp:TreeNode Text="MSN" NavigateUrl="http://www.msn.com" />
<asp:TreeNode Text="MSNBC News" NavigateUrl="http://www.msnbc.msn.com" />
</asp:TreeNode>
<asp:TreeNode Text="Technology">
<asp:TreeNode Text="Microsoft" NavigateUrl="http://www.microsoft.com" />
<asp:TreeNode Text="ASP.NET" NavigateUrl="http://www.asp.net" />
<asp:TreeNode Text="GotDotNet" NavigateUrl="http://www.gotdotnet.com" />
<asp:TreeNode Text="MSDN" NavigateUrl="http://msdn.microsoft.com" />
</asp:TreeNode>
<asp:TreeNode Text="Shopping">
<asp:TreeNode Text="MSN Shopping" NavigateUrl="http://shopping.msn.com" />
<asp:TreeNode Text="MSN Autos" NavigateUrl="http://autos.msn.com" />
</asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="City Links">
<asp:TreeNode Text="MapPoint" NavigateUrl="http://www.mappoint.com" />
<asp:TreeNode Text="MSN City Guides" NavigateUrl="http://local.msn.com" />
</asp:TreeNode>
<asp:TreeNode Text="Music Links">
<asp:TreeNode Text="MSN Music" NavigateUrl="http://music.msn.com" />
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>
如果你觉得有更好的办法,请多多赐教,谢谢了先。
第七棵:父子树的选择【全选/不全选】Asp.Net 2.0 Treeview Checkbox Check/Uncheck All script
http://www.cnblogs.com/OceanChen/archive/2009/01/14/1375707.html
为了使您更好的理解,我简单用中文叙述一下,这个是一棵好树!
这棵树主要解决这样一个场景:我们想,如果我们选择父节点,然后要求父节点下的所有子节点都被选中,我们肯定知道如何做,就是找到父节点,然后循环选择其子节点,这个是不是很好实现啊?呵呵,我想你的回答肯定是没有问题,可是现在增加两个小小的功能:
1. 如果任何一个子节点被反选了,要求这个子节点对应的父节点也被反选了;
2. 如果所有子节点都被选中了,要求与这些子节点对应的父节点也被选中。
怎么样难度很大吧,不要怕,这篇文章就是专门来解决上述两个问题的,好了,废话少说,给大伙来点实际的。
嗯,建议大伙学点英文,^_^,下面就交个您了:
Its a very common requirement to have the parent-child check behaviour in asp.net treeview. To define the problem:
1)Check all the child nodes if the parent is checked and uncheck all child nodes if parent is unchecked ( well, this part is simple).
2)If a node at any level is checked and all its siblings are already checked then the parent node should be checked and the same should apply for the parent node(i.e., if its siblings are checked….), this should happen till the root node.
3)If a node at any level is unchecked then the parents( ma, grand ma, grand grand ma….) up to the root node must be unchecked.
Well there have been scripts on the net that only half accomplished the task(check footnotes). So I wrote the script that solves the problem completely, upto best of my knowledge. I’ve tested in IE 7 and Firefox 2.0, hope it works fine for you all.
Here’s how to implement it:
Step 1: In the page load in code behind file add an attribute to the treeview as:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
If(!isPostBack)
{
TreeView1.Attributes.Add(”onclick”,”OnTreeClick(event)”);
}
The desired affect could also be accomplished by direclty adding the attribute to the treeview tag in .aspx file as: <asp:treeview οnclick=”OnTreeClick(event)”… which would cause Visual Studio to display a warning but it works anyway but the codebehind way of doint it is the right way.
Step 2: Put the below script in the head section of your .aspx page:
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
function OnTreeClick(evt)
{
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == “input” && src.type == “checkbox”);
if(isChkBoxClick)
{
var parentTable = GetParentByTagName(”table”, src);
var nxtSibling = parentTable.nextSibling;
//check if nxt sibling is not null & is an element node
if(nxtSibling && nxtSibling.nodeType == 1)
{
if(nxtSibling.tagName.toLowerCase() == “div”) //if node has children
{
//check or uncheck children at all levels
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
//check or uncheck parents at all levels
CheckUncheckParents(src, src.checked);
}
}
function CheckUncheckChildren(childContainer, check)
{
var childChkBoxes = childContainer.getElementsByTagName(”input”);
var childChkBoxCount = childChkBoxes.length;
for(var i=0;i<checkBoxCount;i++)
{
childChkBoxes[i].checked = check;
}
}
function CheckUncheckParents(srcChild, check)
{
var parentDiv = GetParentByTagName(”div”, srcChild);
var parentNodeTable = parentDiv.previousSibling;
if(parentNodeTable)
{
var checkUncheckSwitch;
if(check) //checkbox checked
{
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if(isAllSiblingsChecked)
checkUncheckSwitch = true;
else
return; //do not need to check parent if any(one or more) child not checked
}
else //checkbox unchecked
{
checkUncheckSwitch = false;
}var inpElemsInParentTable = parentNodeTable.getElementsByTagName(”input”);
if(inpElemsInParentTable.length > 0)
{
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch;
//do the same recursively
CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}function AreAllSiblingsChecked(chkBox)
{
var parentDiv = GetParentByTagName(”div”, chkBox);
var childCount = parentDiv.childNodes.length;
for(var i=0;i<childCount;i++)
{
if(parentDiv.childNodes[i].nodeType == 1)
{
//check if the child node is an element node
if(parentDiv.childNodes[i].tagName.toLowerCase() == “table”)
{
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName(”input”)[0];
//if any of sibling nodes are not checked, return false
if(!prevChkBox.checked)
{
return false;
}
}
}
}
return true;
}
//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;
}
The script is pretty much self explanatory with function names saying it all.
Comments awaited.
Now, see the whole code,
![](http://writeblog.csdn.net/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeViewDemo.Attributes.Add("onclick", "OnTreeClick(event)");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TreeView</title>
<script language="javascript" type="text/javascript">
//************************** Treeview Parent-Child check behaviour ****************************//
function OnTreeClick(evt)
{
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
if(isChkBoxClick)
{
var parentTable = GetParentByTagName("table", src);
var nxtSibling = parentTable.nextSibling;
if(nxtSibling && nxtSibling.nodeType == 1)//check if nxt sibling is not null & is an element node
{
if(nxtSibling.tagName.toLowerCase() == "div") //if node has children
{
//check or uncheck children at all levels
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
//check or uncheck parents at all levels
CheckUncheckParents(src, src.checked);
}
}
function CheckUncheckChildren(childContainer, check)
{
var childChkBoxes = childContainer.getElementsByTagName("input");
var childChkBoxCount = childChkBoxes.length;
for(var i = 0; i<childChkBoxCount; i++)
{
childChkBoxes[i].checked = check;
}
}
function CheckUncheckParents(srcChild, check)
{
var parentDiv = GetParentByTagName("div", srcChild);
var parentNodeTable = parentDiv.previousSibling;
if(parentNodeTable)
{
var checkUncheckSwitch;
if(check) //checkbox checked
{
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if(isAllSiblingsChecked)
checkUncheckSwitch = true;
else
return; //do not need to check parent if any child is not checked
}
else //checkbox unchecked
{
checkUncheckSwitch = false;
}
var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
if(inpElemsInParentTable.length > 0)
{
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch;
//do the same recursively
CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}
function AreAllSiblingsChecked(chkBox)
{
var parentDiv = GetParentByTagName("div", chkBox);
var childCount = parentDiv.childNodes.length;
for(var i=0; i<childCount; i++)
{
if(parentDiv.childNodes[i].nodeType == 1) //check if the child node is an element node
{
if(parentDiv.childNodes[i].tagName.toLowerCase() == "table")
{
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
//if any of sibling nodes are not checked, return false
if(!prevChkBox.checked)
{
return false;
}
}
}
}
return true;
}
//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;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeViewDemo" runat="server" ShowCheckBoxes="All">
<Nodes>
<asp:TreeNode Text="My Computer">
<asp:TreeNode Text="Favorites">
<asp:TreeNode Text="News">
<asp:TreeNode Text="MSN" NavigateUrl="http://www.msn.com" />
<asp:TreeNode Text="MSNBC News" NavigateUrl="http://www.msnbc.msn.com" />
</asp:TreeNode>
<asp:TreeNode Text="Technology">
<asp:TreeNode Text="Microsoft" NavigateUrl="http://www.microsoft.com" />
<asp:TreeNode Text="ASP.NET" NavigateUrl="http://www.asp.net" />
<asp:TreeNode Text="GotDotNet" NavigateUrl="http://www.gotdotnet.com" />
<asp:TreeNode Text="MSDN" NavigateUrl="http://msdn.microsoft.com" />
</asp:TreeNode>
<asp:TreeNode Text="Shopping">
<asp:TreeNode Text="MSN Shopping" NavigateUrl="http://shopping.msn.com" />
<asp:TreeNode Text="MSN Autos" NavigateUrl="http://autos.msn.com" />
</asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="City Links">
<asp:TreeNode Text="MapPoint" NavigateUrl="http://www.mappoint.com" />
<asp:TreeNode Text="MSN City Guides" NavigateUrl="http://local.msn.com" />
</asp:TreeNode>
<asp:TreeNode Text="Music Links">
<asp:TreeNode Text="MSN Music" NavigateUrl="http://music.msn.com" />
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>
可以参考:http://forums.asp.net/t/1367074.aspx
这七棵树中其中有一棵不是树,但是如果作为数据源绑定到树上,那么就和树联系起来了。那么到底那棵不是呢?这个是我留给您的家庭作业!
为了总结方便,有些树我就直接从别处转载了,且一一注明出处了。希望您能从这七棵树得到你想要的东西!同时如果你要更好的意见或建议,请与我联系!由于水平有限,可能会有疏忽之处,请多多指教,共同探讨,共同进步。
![Information](https://i-blog.csdnimg.cn/blog_migrate/25d3c18cc6f09e212b32e167ff71a6ca.png)
出处: http://www.cnblogs.com/OceanChen/
版权:本文版权归作者和博客园共有
转载:欢迎转载,为了保存作者的创作热情,请按【要求】转载,谢谢
要求:未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任