jquery 使用JavaScript在HTML树视图上选择复选框

bqjvbblv  于 2023-10-17  发布在  jQuery
关注(0)|答案(2)|浏览(86)

我目前正在用html和JavaScript开发一个asp.net核心web应用程序。问题是,我试图实现一个树视图,其中每个元素都是一个复选框,当我单击一个元素时,我希望子元素也被选中。你可以看到下面的一个例子:

下面是代码:

@using ProvaFormularis.Assets.TVItems;

@model IEnumerable<MeasurementModel>

@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<style>
    /* Remove default bullets */
    ul, #myUL {
        list-style-type: none;
    }

    /* Remove margins and padding from the parent ul */
    #myUL {
        margin: 0;
        padding: 0;
        overflow-y: scroll;
        height: 450px;
        background: #f9f9f9;
    }

    /* Style the caret/arrow */
    .caret {
        cursor: pointer;
        user-select: none; /* Prevent text selection */
        font-size: large;
    }

        /* Create the caret/arrow with a unicode, and style it */
        .caret::before {
            content: "\25B6";
            color: black;
            display: inline-block;
            margin-right: 6px;
            font-size: large;
        }

    /* Rotate the caret/arrow icon when clicked on (using JavaScript) */
    .caret-down::before {
        transform: rotate(90deg);
    }

    /* Hide the nested list */
    .nested {
        display: none;
    }

    /* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
    .active {
        display: block;
    }

    li {
        padding: 12px;
    }

    label {
        font-size: large
    }

    input[type=checkbox] {
        transform: scale(1.5);
    }
</style>

<form>
    <ul>
        @foreach (TVStandard tvstandard in StaticClass.TVList.StandardsList)
        {
            <li>
                <span class="caret"></span>
                <input type="checkbox" class="checker" [email protected] name="Standard" [email protected] unchecked>
                <label [email protected]>@tvstandard.Name (@tvstandard.folderName)</label>
                <ul class="nested">
                    @foreach(TVSection tvsection in tvstandard.Children)
                    {
                        <li>
                            <span class="caret"></span>
                            <input type="checkbox" class="checker" [email protected] name="Section" [email protected] unchecked>
                            <label [email protected]>@tvsection.Name (@tvsection.scriptName)</label>
                            <ul class="nested">
                                @foreach (TVMode tvmode in tvsection.Children) 
                                {
                                    <li>
                                        <span class="caret"></span>
                                        <input type="checkbox" class="checker" [email protected] name="Mode" [email protected] unchecked>
                                        <label [email protected]>@tvmode.Name</label>
                                        <ul class="nested">
                                            @foreach (TVFreq tvfreq in tvmode.Children) 
                                            {
                                                <li>
                                                    <input type="checkbox" class="checker" [email protected] name="Frequency" [email protected] unchecked>
                                                    <label [email protected]>@tvfreq.Name (@tvfreq.ID)</label>
                                                </li>
                                            }
                                        </ul>
                                    </li>
                                }
                            </ul>
                        </li>
                    }
                </ul>
            </li>
        }
    </ul>
</form>

<script>
    var toggler = document.getElementsByClassName("caret");
    var i;

    for (i = 0; i < toggler.length; i++) {
        toggler[i].addEventListener("click", function () {
            this.parentElement.querySelector(".nested").classList.toggle("active");
            this.classList.toggle("caret-down");
        });
    }
</script>

<script>
    var toggler = document.getElementsByClassName("checker");
    var i;
    for (i = 0; i < toggler.length; i++) {
        toggler[i].addEventListener("click", function () {
            var lis = this.parentElement.getElementsByClassName(".nested").children;
            var j;
            for (j = 0; j < lis.length) {
                var toggler2 = lis.getElementsByClassName("checker");
                var k;
                for (k = 0; k < toggler2.length; k++) { 

                    toggler2[k].click();
                }
            }
        });
    }
</script>

那么,有谁知道如何正确地实现这种行为?

请注意,第一个脚本是删除子元素的脚本,而第二个脚本必须选择查尔兹元素,但不起作用。
PD:我已经测试了点击事件的正确检索和复选框的点击操作,它工作得很好。我已经用这些脚本做到了这一点:

<script>
    var toggler = document.querySelectorAll("input[type=checkbox]");
    var i;
    for (i = 0; i < toggler.length; i++) {
        toggler[i].click();
    }
</script>
<script>
    var toggler = document.querySelectorAll("input[type=checkbox]");
    var i;
    for (i = 0; i < toggler.length; i++) {
        toggler[i].addEventListener("click", function () {
            this.checked = true;
        });
    }
</script>
v9tzhpje

v9tzhpje1#

在第二个脚本中,for循环中有一个语法错误。应该是for (j = 0; j < lis.length; j++)而不是for (j = 0; j < lis.length)
不应该使用.getElementsByClassName(),而应该使用.querySelectorAll()来按类名选择元素。
当您使用lis.getElementsByClassName("checker")时,它将返回一个HTMLCollection,因此您需要遍历它。

var toggler = document.getElementsByClassName("checker");
var i;

for (i = 0; i < toggler.length; i++) {
    toggler[i].addEventListener("click", function () {
        var lis = this.parentElement.querySelector(".nested").children;
        var j;

        for (j = 0; j < lis.length; j++) {
            var toggler2 = lis[j].querySelectorAll(".checker");
            var k;

            for (k = 0; k < toggler2.length; k++) {
                toggler2[k].checked = this.checked;
            }
        }
    });
}
muk1a3rh

muk1a3rh2#

如果您能够使用jQuery完成此任务,它将大大简化您的过程。您的目标是动态地为每个具有特定ID的父复选框分配一个属性,例如'data-parent-$id',同时将该父复选框的ID作为类分配给其子元素。通过实现这种方法,您将能够创建无限的父子树层次结构,每个树都带有复选框。有关实际演示,请参考以下代码示例。

$(document).ready(function() {
            // Attach a change event to all checkboxes in the tree
            $('.checkbox-tree :checkbox').change(function() {
                var isChecked = $(this).prop('checked');
                var $parent_id = $(this).data('parent');
                selectChildren($parent_id, isChecked);
                
            });

            // Function to select all children checkboxes
            function selectChildren($parent_id, isChecked) {
                $('.checkbox-tree').find('.child_of_'+$parent_id).not(this).prop('checked', isChecked);
                $('.checkbox-tree').find('.child_of_'+$parent_id).trigger('change');
            }

        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Checkboxes</title>
    </head>
    <body>
        <div class="checkbox-tree">
            <label><input type="checkbox" value="1" data-parent="1"> Parent 1</label>
            <ul>
                <li><label><input type="checkbox" class="child_of_1" data-parent="2" value="2"> Child 1.1</label></li>
                <li><label><input type="checkbox" class="child_of_1" data-parent="3" value="3"> Child 1.2</label></li>

                <ul>
                    <li><label><input type="checkbox" class="child_of_3" value="2"> Child 1.1</label></li>
                    <li><label><input type="checkbox" class="child_of_3" value="3"> Child 1.2</label></li>
                </ul>
            </ul>
        </div>    
    </body>
</html>

相关问题