我希望用颜色选项填充选择字段。到目前为止我有这个:
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";
}
任何想法我需要使用什么格式来添加它?
使用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>
后
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();