使用JavaScript动态生成选择选项下拉菜单

Dynamically generated select option dropdown menu using JavaScript

本文关键字:选择 选项 下拉菜单 JavaScript 动态 使用      更新时间:2023-09-26

这是我要创建的选择菜单。但正如你所看到的,这是静态数据。由于我实际上有一堆从后端servlet传递的JSON数据,因此将有数百个选项项。我想要动态生成选项菜单为我的下拉框。

<select id="brand-select" name="brand">
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
    <option value="lexus">Lexus</option>
</select>

这是我的尝试,它不工作:

HTML:

<select id="brand-select" name="brand" onChange="createOptions">
    <option value="none"></option>
</select>
JavaScript:

//Asssume I have jsonDataForBrands ready, and it contains 100s items
function createOptions() {
    for (var fieldIndex in jsonDataForBrands) {
        html += '<option value=' + fieldIndex  + '>' + jsonDataForBrands[field].title + '</option>';
}

我自己弄明白了…

HTML:

<select id="brand-select" name="brand">
                </select>
JavaScript:

function creatBrandOptions(){
    for (var field in jsonDataForBrands) {
         $('<option value="'+ jsonDataForBrands[field].name +'">' + jsonDataForBrands[field].title + '</option>').appendTo('#brand-select');
    }
}

我做了一个Ajax调用从我的servlet检索JSON数据,然后creatBrandOptions()在同一函数BTW…

你先我一步。下面是一个使用jquery向select添加选项的完整简化示例:

<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<button id="populateMenu" >Populate menu</button>
<select id="mySelect">

</select>
<script>
    var optionValues= [[1,"first"],[2,"second"]];
    jQuery("#populateMenu").click( function () {
        for (var i=0;i<optionValues.length;i++){
            jQuery('#mySelect').append(jQuery("<option></option>").val(optionValues[i][0]).text(optionValues[i][1]))
        }
    });
</script>
</body>
</html>

这个例子使用jQuery。看看是否适合你:

function createOptions( jsonDataForBrands ) {
   $('#brand-select option').remove(); // first remove all options
   for (var i=0; i<jsonDataForBrands.length; i++)
   for (var fieldIndex in jsonDataForBrands) { // then populatem them
      $('#brand-select').append($("<option></option>").attr("value", fieldIndex  ).text(jsonDataForBrands[field].title) );
}