使用javascript循环下拉html数组

时间:2015-10-03 18:16:29

标签: javascript html loops for-loop dropdown

我正在尝试使用javascript数组填充下拉菜单。我可以显示单个元素,但不能显示整个数组。我确定之前已经问过这个问题,但找不到任何参考资料。任何帮助将不胜感激。

var sex=["male","female", "unknown"];

for (i=0;i<sex.length;i++){
var opt = document.createElement("option");
document.getElementById("m").innerHTML=sex[i];
}

html是:

    <form name = "demo">
    <table id = "demo">
    <th>Demographics</th>
    <tr><td>Sex</td><td><select><option id="m"></option></select></td></tr>
    </table>
    </form>

3 个答案:

答案 0 :(得分:1)

请参阅下面针对您的问题的非优雅修复程序。如果使用JQuery库,可以将其重构为更好看的代码,例如参见What is the best way to add options to a select from an array with jQuery?

&#13;
&#13;
var sex = ["male", "female", "unknown"];

for (i = 0; i < sex.length; i++) {
  var opt = document.createElement("option");
  document.getElementById("m").innerHTML += '<option id="' + i + '">' + sex[i] + '</option>';
}
&#13;
<form name="demo">
  <table id="demo">
    <th>Demographics</th>
    <tr>
      <td>Sex</td>
      <td>
        <select id="m">

        </select>
      </td>
    </tr>
  </table>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是我通常使用的方法:

Codepen Demo

HTML:

<form name="demo">
  <table id="demo">
    <th>Demographics</th>
    <tr>
      <td>Sex</td>
      <td>
        <select id = "sex">

        </select>
      </td>
    </tr>
  </table>
</form>

使用Javascript:

//array to hold the persons sex
var sex = ["male", "female", "unknown"];

//array to store html to add to the select list
var html = [];

//loop through the array
for (var i = 0; i < sex.length; i++) {//begin for loop

  //add the option elements to the html array
  html.push("<option>" + sex[i] + "</option>")

}//end for loop

//add the option values to the select list with an id of sex
document.getElementById("sex").innerHTML = html.join("");

答案 2 :(得分:0)

使用模板库,如下划线或把手或小胡子。从javascript生成html的不良做法。