我有一个数组,我希望数组中的每个值都作为选项显示在输入选择框中。这就是我自己试过的:
<select>
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for(cars)
{
document.write("<option>"cars"</option>");
}
</script>
</select>
答案 0 :(得分:2)
使用这个javascript应该是这样的
<select id="MySelectBox">
</select>
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for (i=0; i<cars.length; i++) {
option+= "<option value='"+cars[i]+"'>"+cars[i]+"</option>";
}
document.getElementById("MySelectBox").html= option;
</script>
答案 1 :(得分:1)
你可以轻松地使用for循环
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for(var i=0;i<cars.length;i++)
{
var diVContent = '<option>'+cars[i]+'</option>';
document.write(diVContent);
}
</script>
答案 2 :(得分:0)
您可以使用以下代码并尝试:
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var select_c = '<select>';
for(var i=0;i<cars.length;i++)
{
select_c += '<option>'+cars[i]+'</option>';
}
select_c += '</select>';
document.write(select_c);
</script>
你可以在这里看到小提琴:Demo