javascrip实现:若选中TreeView的父节点checkbox,则其子节点全部选中
1:选中父节点的时候,其子节点将自动选中;
2:若父节点不选中,其子节点也全部选中;
2:若其中一个子节点uncheck的时候,其父节点的状态就不选中。
该方法在IE7 和firefox下均可执行:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!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" language="javascript">
function client_OnTreeNodeChecked(evt){
var obj = getCurrentNode(evt);
var treeNodeFound = false;
var checkedState;
if (obj.tagName == "INPUT" && obj.type == "checkbox" ){
checkedState = obj.checked;
var curNode = getParentNode(obj);
changeNodeState(curNode,checkedState);
}
}
function getCurrentNode(evt){
var obj;
if(window.event) obj = window.event.srcElement;
else obj = (evt ? evt : (window.event ? window.event : null)).target;
return obj;
}
function getParentNode(node){
do
{
node = node.parentNode;
}
while (node.tagName != "TABLE")
return node;
}
function changeNodeState(node,state){
//change all the children
if(node.nextSibling!=null && node.nextSibling.tagName=="DIV"){
var cbArr = node.nextSibling.getElementsByTagName("INPUT");
for(var i=0; i<cbArr.length; i++){
if(cbArr[i].type == "checkbox") cbArr[i].checked = state;
}
}
//change its parents' state
var flag = true;
var inputArr = node.parentNode.getElementsByTagName("INPUT");
if(state){
for(var i=0; i<inputArr.length; i++){
if(inputArr[i].type == "checkbox" && !inputArr[i].checked) flag = false;
}
}
else flag = true
if(flag){
var parentArr = node.parentNode.previousSibling.getElementsByTagName("INPUT");
for(var i=0; i<parentArr.length; i++){
if(parentArr[i].type == "checkbox") parentArr[i].checked = state;
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1"
ShowCheckBoxes="None" onclick="client_OnTreeNodeChecked(event)"
ontreenodedatabound="TreeView1_TreeNodeDataBound"
ondatabound="TreeView1_DataBound" onprerender="TreeView1_PreRender">
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>
</div>
</form>
</body>
</html>