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

1

これは、私が通常使用する方法です。

コードペンデモ

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 に答える