首先在TV_DustList绑定完数据后,为控件注册客户端事件:
后台代码如下
TV_DustList.Attributes.Add("onclick", "postBackByObject()"); //注册客户端事件
然后在页面中添加如下JS方法
<script type="text/javascript">
function postBackByObject() {
var o = window.event.srcElement;
//判断激发的对象是否为checkbox,如果是则激发__doPostBack("","");
//因为前台生成的checkbox是"<input type='checkbox'./> "
//所以判断如下:
var ele = window.event.srcElement;
if (o.tagName == "INPUT" && o.type == "checkbox") {
// __doPostBack("",""); //注意:__doPostBack中为两个下划线组成"_"
// var arr = o.parentNode.children;
// var len = arr.length;
// if (len > 0) {
// for(var i=0;i<len;i++)
// {
// if(arr[i].tagName=="INPUT" && arr[i].type=="checkbox")
// arr[i].checked=o.checked;
// }
// }
ele.className = "";
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;
}
}
setParentClassName(ele);
}
}
function setParentClassName(currCheckBox) {
var objParentNode = public_GetParentNode(currCheckBox);
if (public_IsObjectNull(objParentNode))
return;
var checkBoxs = objParentNode.getElementsByTagName("INPUT");
var allSelect = true;
var allUnSelect = true;
for (var i = 0; i < checkBoxs.length; i++) {
if (checkBoxs[i].type == 'checkbox') {
if (checkBoxs[i].checked) allUnSelect = false;
else allSelect = false;
if ((!allSelect) && (!allUnSelect)) break;
}
}
var objParentCheckBox = public_Node2CheckBox(objParentNode);
if (public_IsObjectNull(objParentCheckBox)) return;
setParentClassName(objParentCheckBox);
if (allSelect) {
objParentCheckBox.className = "";
objParentCheckBox.checked = true;
return;
}
if (allUnSelect) {
objParentCheckBox.className = "";
objParentCheckBox.checked = false;
return;
}
objParentCheckBox.checked = false;
objParentCheckBox.className = "parentbox_style";
}
//得到本节点所在的Node(Div对象)
function public_GetParentNode(element) {
var parent = element.parentNode;
var upperTagName = "DIV";
//如果这个元素还不是想要的tag就继续上溯
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function public_Node2CheckBox(element) {
var objID = element.getAttribute("ID");
objID = objID.substring(0, objID.indexOf("Nodes"));
return document.getElementById(objID + "CheckBox");
}
function public_IsObjectNull(element) {
if (element == null || element == "undefined")
return true;
else
return false;
}
</script>
页面 TreeView 控件
<asp:TreeView ID="TV_DustList" runat="server" Font-Size="12px" ForeColor="#000" ExpandDepth="0" CssClass="TV_DustList"
Height="100%" ShowCheckBoxes="All" ShowLines="True">
<LeafNodeStyle ForeColor="#d68800" />
<RootNodeStyle HorizontalPadding="0px" />
<SelectedNodeStyle BackColor="#FF99CC" ChildNodesPadding="2px" CssClass="TreeClass"
Font-Size="14px" Font-Bold="True" />
</asp:TreeView>