4

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

3 回答 3

2

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

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>

于 2015-10-03T18:33:22.720 回答
1

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

Codepen 演示

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("");
于 2015-10-03T18:26:56.863 回答
0

使用模板库,如下划线或车把或小胡子。从 javascript 生成 html 是一种不好的做法。

于 2015-10-03T19:23:26.187 回答