首页 > 解决方案 > 如何调整下拉菜单的高度 with JavaScript? I have a <select> which should load its options from the server when clicked. While trying to do so there was a small problem I couldn't get over which is that the height of the dropdown box wouldn't expand autom

问题描述

标签: javascripthtml

解决方案


问题是您在单击下拉菜单时加载项目。在项目加载之前,您已经展开下拉列表。如果您单击它并重新打开它,它将是正确的大小。解决方案是在单击下拉列表之前加载项目。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        var data = JSON.parse("[{\"name\":\"EE&CS\",\"id\":1},{\"name\":\"Management\",\"id\":2},{\"name\":\"Subjects\",\"id\":3},{\"name\":\"Other\",\"id\":32},{\"name\":\"Test\",\"id\":33}]");
        window.onload = function () {
            var select = document.getElementById("select-test");

            for (var i = 0; i < data.length; i++) {
                var subject = data[i];
                select.appendChild(getNode("<option value=\"" + subject.id + "\">" + subject.name + "</option>"));
            }
        };

        function getNode(str) {
            return new DOMParser().parseFromString(str, "text/html").body.childNodes[0];
        }
    </script>
</head>
<body>
<select id="select-test" data-loaded="0">
    <option value="" disabled selected>-- Choose subject --</option>
</select>
</body>
</html>


推荐阅读