答案 0 :(得分:4)
您可以使用数组的.map()
函数来执行此操作。使用这种方式:
var color = ["#AAAAAA" , "#FF9992", "#BF9232"];
$("#button1").click(function() {
$("div").append("<select />");
var html = "";
color.map(function (clr) {
html += '<option style="background: ' + clr + ';">' + clr + '</option>';
});
$("select").append(html);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="button1">Click</button>
<div></div>
&#13;
如果您希望<select>
根据<option>
更改背景颜色,则可以执行以下操作:
var color = ["#AAAAAA" , "#FF9992", "#BF9232"];
$("#button1").click(function() {
$("div").append("<select />");
var html = "";
color.map(function (clr) {
html += '<option style="background: ' + clr + ';">' + clr + '</option>';
});
$("select").append(html).change(function () {
$(this).css("background", $(this).val());
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="button1">Click</button>
<div></div>
&#13;
答案 1 :(得分:1)
我建议使用纯JavaScript的其他解决方案。
var color = ["#AAAAAA" , "#FF9992", "#BF9232"];
function addOptions(arr, selectId) {
var s = document.getElementById(selectId);
if (!s) {
s = document.createElement("select");
var myDiv = document.getElementById("box");
myDiv.appendChild(s);
s.id = selectId;
}
s.options.length = 0;
for (var i = 0; i < arr.length; i++) {
var option = document.createElement('option');
option.text = arr[i];
option.style.backgroundColor = arr[i];
option.value = arr[i];
s.options[s.options.length] = option;
}
}
document.getElementById("button").onclick = function () {
addOptions(color, "second");
};
&#13;
<button id="button">Click me</button>
<div id="box"></div>
&#13;