用Javascript对象选择字段

时间:2018-03-05 21:59:50

标签: javascript object select

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

 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";
 }

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

2 个答案:

答案 0 :(得分:0)

使用colors数组以及函数add

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

&#13;
&#13;
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)));
&#13;
<select id="color"></select>
&#13;
&#13;
&#13;

答案 1 :(得分: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