[select2] 分组下拉选择

<html>
<header>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</header>

<body>
    <select id="selectBuildingCell"></select>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>

        let building = [];

        for (var i = 0; i < 3; i++) {

            let cell = [];
            for (var j = 0; j < 5; j++) {
                cell.push({
                    id: j,
                    text: `Cell${j}`
                });
            }

            if (cell.length > 0) {
                building.push({
                    text: `Building${i}`,
                    children: cell
                });
            }
        }

        $("#selectBuildingCell").select2({ data: building, width: '100%', sorter: opt => opt.sort((a, b) => a.text.localeCompare(b.text)) });

    </script>
</body>

</html>

 

posted @ 2023-01-10 10:44  WikiChen  阅读(222)  评论(0编辑  收藏  举报