学习 jQuery - 6 在 TreeView 中实现全选

在 VisualStudio 2005 中, ASP.NET 有一个非常方便的树型控件 TreeView,我们可以开启它的 checkbox 功能,实现选择。但是,在默认方式下,TreeView 没有自动选择下级节点的功能,我们可以使用 jQuery 为它增加这个功能。

分析 TreeView 生成的 Html 可以发现,每层节点都保存在 table 元素中,如果节点又下层节点,则 table 元素的下一个元素为 div 元素,div 元素中包含一个 表示下层节点的 table 元素,下层节点的复选框就位于其中。

通过 jQuery 的 parents 函数和 next 函数,可以完成以上的选择。

函数说明:

parents 取得指定的父元素,可以逐级向上进行查找。

next 取得当前元素的下一个元素,可以通过参数进行过滤

checked 设置或者取得当前元素的选择状态

页面内容如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TreeViewDemo._Default" %>

<!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" src=“jquery-1.2.5.js"></script>

<script type ="text/javascript" >

$(function() {

$(":checkbox").click(function() {

var v = this.checked;

$(this).parents("table").next("div").find(":checkbox").each(function() {

this.checked = v;

});

});

});

</script>

</head>

<body>

<form >

<div>

<asp:TreeView runat="server"

Height="300px"

Width="200px"

ShowCheckBoxes="All" >

<Nodes>

<asp:TreeNode>

<asp:TreeNode Text="One" Value="One">

<asp:TreeNode Text="1" Value="1"></asp:TreeNode>

<asp:TreeNode Text="2" Value="2"></asp:TreeNode>

<asp:TreeNode Text="3" Value="3"></asp:TreeNode>

</asp:TreeNode>

<asp:TreeNode Text="Two" Value="Two">

<asp:TreeNode Text="1" Value="1"></asp:TreeNode>

<asp:TreeNode Text="2" Value="2"></asp:TreeNode>

</asp:TreeNode>

<asp:TreeNode Text="Three" Value="Three"></asp:TreeNode>

<asp:TreeNode Text="Four" Value="Four"></asp:TreeNode>

</asp:TreeNode>

</Nodes>

</asp:TreeView>

</div>

</form>

</body>

</html>