asp.net treeview 控件父子节点级联选中
一、使用方法
- <asp:TreeView ID="MenuTree" runat="server" ShowCheckBoxes="All" >
- </asp:TreeView>
- <script type="text/javascript" language="javascript">
- SetTreeNodeAutoSelectParentNodeHandle("<%=MenuTree.ClientID%>");
- </script>
二、Javascript函数
- function AutoSelectTreeNodeChecked(ele) {
- // var ele = window.event.srcElement;
- if (ele.type == 'checkbox') {
- //选中父节点(只选中父节点,不选中父节点的子节点)
- AutoSelectParentNode(ele);
- var childrenDivID = ele.id.replace('CheckBox', 'Nodes');
- var div = document.getElementById(childrenDivID);
- if (div == null) return;
- var checkBoxs = div.getElementsByTagName('INPUT');
- //选中所有子节点
- for (var i = 0; i < checkBoxs.length; i++) {
- if (checkBoxs[i].type == 'checkbox')
- checkBoxs[i].checked = ele.checked;
- }
- }
- }
- //用Treeview chekbox节点自动选择父节点的处理事件
- function AutoSelectParentNode(obj) {
- if (obj.checked) {
- try {
- var p = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
- if (p) {
- var pCheckNodeID = p.id.replace("Nodes", "CheckBox");
- var checkNode = document.getElementById(pCheckNodeID);
- if (checkNode) {
- //checkNode.click(); //如果不需要选中所有父节点的话(如父的父等)把本行代码去掉及可
- checkNode.checked = true;
- AutoSelectParentNode(checkNode);
- }
- }
- } catch (ex) { }
- }
- }
- //用于给TreeView的 chebox添加 自动选择父节点的处理事件(如果要将某一TreeView变为自动选择父节点 只需调用下面方法)
- function SetTreeNodeAutoSelectParentNodeHandle(treeID) {
- var objs = document.getElementsByTagName("input");
- for (var i = 0; i < objs.length; i++) {
- if (objs[i].type == 'checkbox') {
- var obj = objs[i];
- if (obj.id.indexOf(treeID) != -1) {
- objs[i].onclick = function() { AutoSelectTreeNodeChecked(this); };
- }
- }
- }
- }