Asp.Net 带有复选框选择的 TreeView 仅适用于第一页加载。

Asp.Net TreeView with checkBox selection works only on first page Load.

我正在使用 TreeViewShowCheckBoxes="All"。我想用下面的代码实现的是,当用户单击 Parent node 时,所有 child nodes 都会得到 selected。 :

此代码仅适用于第一页加载。例如。我单击“Fruits”,所有 child nodes 都被选中,当我再次单击时,所有 child nodes 都被取消选择。到目前为止,一切都很好。但是,当我再次单击“Fruits”时,child nodes 不会被选中。我认为问题出在我的 jquery 代码中。

ascx 文件:

<asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All"></asp:TreeView>

后面的代码:

 if (!IsPostBack)
            {
                TreeView1.Nodes.Add(new TreeNode("Fruits", "Fruits"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Mango", "Mango"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Apple", "Apple"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Pineapple", "Pineapple"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Orange", "Orange"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Grapes", "Grapes"));

                TreeView1.Nodes.Add(new TreeNode("Vegetables", "Vegetables"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Carrot", "Carrot"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Cauliflower", "Cauliflower"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Potato", "Potato"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Tomato", "Tomato"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Onion", "Onion"));

            }

ascx 文件:

<script type="text/javascript">

        $(document).ready(function() {

            $("[id*=TreeView1] input[type=checkbox]").bind("click", function () {
                var table = $(this).closest("table");
                if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
                    //Is Parent CheckBox
                    var childDiv = table.next();
                    var isChecked = $(this).is(":checked");
                    $("input[type=checkbox]", childDiv).each(function () {
                        if (isChecked) {
                            $(this).attr("checked", "checked");
                        } else {
                            $(this).removeAttr("checked");
                        }
                    });
                } else {
                    //Is Child CheckBox
                    var parentDIV = $(this).closest("DIV");
                    if ($("input[type=checkbox]", parentDIV).length == $("input[type=checkbox]:checked", parentDIV).length) {
                        $("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
                    } else {
                        $("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
                    }
                }
            });


        });

您可以改用 .prop,attr 有时会有奇怪的行为。

选中

.prop('checked',true);

未选中

.prop('checked',false);