使用 javascript 循环下拉 html 数组

using javascript to loop through drop down html array

我正在尝试使用 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>

这是我通常使用的有效方法:

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("");

请参阅下面对您的问题的非优雅修复。如果您使用 JQuery 库,您可以将其重构为更好看的代码,例如参见 [​​=12=]

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>';
}
<form name="demo">
  <table id="demo">
    <th>Demographics</th>
    <tr>
      <td>Sex</td>
      <td>
        <select id="m">

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

使用下划线、车把或小胡子等模板库。从 javascript.

生成 html 是不好的做法