用Javascript对象选择字段

问题描述 投票:0回答:2

我希望用颜色选项填充选择字段。到目前为止我有这个:

 function getFruit() {
 var x = document.getElementById("myinput").value;
 var score;
 var picture;
 if (x === "Apple") {
 score = "A";
 picture = "http://exampple.com/assets/apple.jpg";
 }
else if (x === "Banana") {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;

}

<input type="text" id="text">
<img id="display" />
<select id="color"></color>

但我想用一个颜色选项填充一个选择字段,如:

if (x === "Apple") {
 score = "A";
 picture = "http://exampple.com/assets/apple.jpg";
 color = "Red" "Green" Blue";
 }

任何想法我需要使用什么格式来添加它?

javascript object select
2个回答
0
投票

使用colors数组以及add函数:

.add(new Option(c, value));

var colors = ["Red", "Green", "Blue"];
var sel = document.getElementById('color');

colors.forEach((c, value/*This is the index of this loop*/) => sel.add(new Option(c, value)));
<select id="color"></select>

0
投票

if(x === "Apple") {
    score = "A";
    picture = "http://exampple.com/assets/apple.jpg";
    colors = ["Red", "Green", Blue"];
 }

使用reduce方法生成一个选项字符串,并将其分配给颜色选择框的内部html。

document.getElementById("color").innerHTML = color.map((color) => '<option value="' + color+ '">' +color +'</option>').join();

http://jsbin.com/kuyazekivu/edit?html,js,console,output

© www.soinside.com 2019 - 2024. All rights reserved.