当前位置 : 主页 > 网络编程 > JavaScript >

asp.net实现 treeview选中父节点其子节点也选

来源:互联网 收集:自由互联 发布时间:2021-06-30
1.在前台添加JS脚本 function CheckEvent(evt) { evt = window.event || evt; var objNode = evt.srcElement || evt.target; if (objNode.tagName == "INPUT" objNode.type == "checkbox") { var objParentDiv = objNode.id.replace("CheckBox", "Node
1.在前台添加JS脚本
function CheckEvent(evt) {
            evt = window.event || evt;
            var objNode = evt.srcElement || evt.target;
            if (objNode.tagName == "INPUT" && objNode.type == "checkbox") {
                var objParentDiv = objNode.id.replace("CheckBox", "Nodes");
                if (objNode.checked == true) {
                    setChildCheckState(objParentDiv, true);

                    setParentCheckeState(objNode, true);
                }
                else {
                    setChildCheckState(objParentDiv, false);

                    if (!HasOtherChecked(objNode)) {
                        setParentCheckeState(objNode, false);
                    }
                }
            }
        }

        //判断是否有并行的其他节点被选中
        function HasOtherChecked(objNode) {
            var objParentDiv = WebForm_GetParentByTagName(objNode, "div");

            var chks = objParentDiv.getElementsByTagName("INPUT");
            for (var i = 0; i < chks.length; i++) {
                if (chks[i].checked && chks[i].id != objNode.id) {
                    return true;
                }
            }
            return false;
        }

        //设置父节点
        function setParentCheckeState(objNode, chkstate) {
            try {
                var objParentDiv = WebForm_GetParentByTagName(objNode, "div");

                if (objParentDiv == null || objParentDiv == "undefined ") {
                    return;
                }
                else {
                    var objParentChkId = objParentDiv.id.replace("Nodes", "CheckBox");
                    var objParentCheckBox = document.getElementById(objParentChkId);

                    if (objParentCheckBox) {
                        objParentCheckBox.checked = chkstate;
                        setParentCheckeState(objParentDiv, chkstate);
                    }
                }
            }
            catch (e) { }
        }

        //设置子节点
        function setChildCheckState(nodeid, chkstate) {
            var node = document.getElementById(nodeid);

            if (node) {
                var chks = node.getElementsByTagName("INPUT");
                for (var i = 0; i < chks.length; i++) {
                    chks[i].checked = chkstate;
                }
            }
        }
2.在Page_Load中进行注册事件
protected void Page_Load(object sender, EventArgs e) {
    TreeView1.Attributes.Add("onclick", "CheckEvent(event)");
}

// 原文来自http://www.cnblogs.com/SethKing/p/6032616.html
网友评论