主要的实现原理是在TreeView控件的onclick事件中用JS实现全选操作。
<script language="javascript" type="text/javascript">
function OnTreeNodeChecked()
{
var ele = event.srcElement;
if(ele.type=='checkbox')
{
var childrenDivID = ele.id.replace('CheckBox','Nodes');
var div = document.getElementById(childrenDivID);
if(div != null)
{
var checkBoxs = div.getElementsByTagName('INPUT');
for(var i=0;i<checkBoxs.length;i++)
{
if(checkBoxs[i].type=='checkbox')
checkBoxs[i].checked=ele.checked;
}
}
else
{
var div = GetParentByTagName(ele,'DIV');
var checkBoxs = div.getElementsByTagName('INPUT');
var parentCheckBoxID = div.id.replace('Nodes','CheckBox');
var parentCheckBox = document.getElementById(parentCheckBoxID);
for(var i=0;i<checkBoxs.length;i++)
{
if(checkBoxs[i].type=='checkbox' && checkBoxs[i].checked)
{
parentCheckBox.checked = true;
return;
}
}
parentCheckBox.checked = false;
}
}
}
function GetParentByTagName(element, tagName)
{
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName))
{
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
</script>
function OnTreeNodeChecked()
{
var ele = event.srcElement;
if(ele.type=='checkbox')
{
var childrenDivID = ele.id.replace('CheckBox','Nodes');
var div = document.getElementById(childrenDivID);
if(div != null)
{
var checkBoxs = div.getElementsByTagName('INPUT');
for(var i=0;i<checkBoxs.length;i++)
{
if(checkBoxs[i].type=='checkbox')
checkBoxs[i].checked=ele.checked;
}
}
else
{
var div = GetParentByTagName(ele,'DIV');
var checkBoxs = div.getElementsByTagName('INPUT');
var parentCheckBoxID = div.id.replace('Nodes','CheckBox');
var parentCheckBox = document.getElementById(parentCheckBoxID);
for(var i=0;i<checkBoxs.length;i++)
{
if(checkBoxs[i].type=='checkbox' && checkBoxs[i].checked)
{
parentCheckBox.checked = true;
return;
}
}
parentCheckBox.checked = false;
}
}
}
function GetParentByTagName(element, tagName)
{
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName))
{
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
</script>
剩下的就是TreeView控件绑定的onclick事件了。
<asp:TreeView ID="TreeView1" runat="server" onclick="OnTreeNodeChecked()" ShowCheckBoxes="All" ExpandDepth="2" Width="100%" Height="100%">
</asp:TreeView>
至此实现了所有的用JS实现TreeView控件的全选与部分选择的问题。
</asp:TreeView>