填充<select>用Javascript函数

fill a <select> with a function Javascript

本文关键字:Javascript 函数 select 填充      更新时间:2023-09-26

我创建了一个函数,其中包含一个我想添加到HTML中的字符串。但是当我测试它时,它不会显示在我的表中声明的选项。

function test(){
  // table already defined
  var choices = "<option selected>Select...</option>";
  for (var i=0; i<tableOptions.length; i++) {
    choices += "<option>" + tableOptions[i][0] +"</option>"; 
  }
  document.getElementById("theOptions").innerHTML = choices;
}

在我的HTML中我有

<select id="theOptions"></select> 

我做错了什么?

顺便说一下,我的test()会在我的页面显示后自动加载。

<body onload="test()">

参见如何在javascript中填充select元素的选项,详细了解如何创建和附加选项到现有的<select>元素。

使用该方法,这似乎最接近你得到的:

var select = document.getElementById("theOptions");
opt = document.createElement("option");
opt.innerHTML = "Select...";
select.appendChild(opt);
for(var i = 0; i < tableOptions.length; i++)
{
   var opt = document.createElement("option");
   opt.innerHTML = tableOptions[i][0];
   select.appendChild(opt);
}