初学者Javascript数组下拉列表

时间:2016-11-26 17:59:42

标签: javascript

新手JS在这里,我需要从10个城市的数组填充下拉列表,我无法获得任何代码。

<select id="selectCity">
<option>Choose a City</option>
</select>

var select = document.getElementById('selectCity');
var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];

//what code will work in this loop below???

for(var i = 0; i < options.length; i++) { 

}

3 个答案:

答案 0 :(得分:2)

试试这段代码。

var select = document.getElementById('selectCity');
var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}​

答案 1 :(得分:2)

试试这个

var select = document.getElementById('selectCity');
var options = ["Winthrop", "Revere", "Malden", "East Boston", "Medford", "Somerville", "South Boston", "Quincy", "Malden", "Weymouth"];

//what code will work in this loop below???

var s = document.getElementById("selectCity");
for (var i = 0; i < options.length; i++) {
  s.innerHTML += `<option value=${i}> ${options[i]}</option>`;
}
<select id="selectCity">
  <option>Choose a City</option>
</select>

答案 2 :(得分:1)

这对你有用!

您只需将此代码放入循环中:

var option = document.createElement(“option”);

option.text = options [i];

option.value = options [i];

select.appendChild(可选);

<select id="selectCity">
    <option>Choose a City</option>
</select>

<script type="text/javascript">
    var select = document.getElementById('selectCity');
    var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];
    for(var i = 0; i < options.length; i++) {
        var option = document.createElement("option");
        option.text = options[i];
        option.value = options[i];
        select.appendChild(option);
    }
</script>