<script type="text/javascript">
//入口函数
function OnCheckEvent() {
var objNode = event.srcElement;
if (objNode.tagName != "INPUT" || objNode.type != "checkbox")
return;
//获得当前树结点
var ck_ID = objNode.getAttribute("ID");
var node_ID = ck_ID.substring(0, ck_ID.indexOf("CheckBox")) + "Nodes";
var curTreeNode = document.getElementById(node_ID);
//级联选择
SetChildCheckBox(curTreeNode, objNode.checked);
SetParentCheckBox(objNode);
}
//子结点字符串
var childIds = "";
//获取子结点ID数组
function GetChildIdArray(parentNode) {
if (parentNode == null)
return;
var childNodes = parentNode.children;
var count = childNodes.length;
for (var i = 0; i < count; i++) {
var tmpNode = childNodes[i];
if (tmpNode.tagName == "INPUT" && tmpNode.type == "checkbox") {
childIds = tmpNode.id + ":" + childIds;
}
GetChildIdArray(tmpNode);
}
}
//设置子结点的checkbox
function SetChildCheckBox(parentNode, checked) {
if (parentNode == null)
return;
var childNodes = parentNode.children;
var count = childNodes.length;
for (var i = 0; i < count; i++) {
var tmpNode = childNodes[i];
if (tmpNode.tagName == "INPUT" && tmpNode.type == "checkbox") {
tmpNode.checked = checked;
}
SetChildCheckBox(tmpNode, checked);
}
}
//设置父结点的checkbox
function SetParentCheckBox(childNode) {
if (childNode == null)
return;
var parent = childNode.parentNode;
if (parent == null || parent == "undefined")
return;
do {
parent = parent.parentNode;
}
while (parent && parent.tagName != "DIV");
if (parent == "undefined" || parent == null)
return;
var parentId = parent.getAttribute("ID");
var objParent = document.getElementById(parentId);
childIds = "";
GetChildIdArray(objParent);
//判断子结点状态
childIds = childIds.substring(0, childIds.length - 1);
var aryChild = childIds.split(":");
var result = false;
//当子结点的checkbox状态有一个为true,其父结点checkbox状态即为true,否则为false
for (var i in aryChild) {
var childCk = document.getElementById(aryChild[i]);
if (childCk.checked)
result = true;
}
parentId = parentId.replace("Nodes", "CheckBox");
var parentCk = document.getElementById(parentId);
if (parentCk == null)
return;
if (result)
parentCk.checked = true;
else
parentCk.checked = false;
SetParentCheckBox(parentCk);
}
</script>
<div>
<asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All" οnclick="OnCheckEvent()"
ShowExpandCollapse="False">
<Nodes>
<asp:TreeNode Text="New Node1" Value="New Node1">
<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 Node2" Value="New Node2">
<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>
<asp:TreeNode Text="New Node3" Value="New Node3"></asp:TreeNode>
</Nodes>
</asp:TreeView>
</div>
//不可修改的checkbox的字体取消灰色
$(document).ready(function () {
$("span").removeAttr("disabled");
});