我希望用颜色选项填充选择字段。到目前为止,我有这个:
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";
}
任何想法我需要使用哪种格式来添加它?
答案 0 :(得分: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)));
&#13;
<select id="color"></select>
&#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();