[英]How should I show list of array colors in a <select>
I am a newbie, and I am not sure how to achieve what I want.我是新手,我不知道如何实现我想要的。 Well, I have this piece of code, which I am learning currently.
好吧,我有这段代码,我目前正在学习。
var color = ["#AAAAAA" , "#FF9992", "#BF9232"];
$("#button1").click(function() {
// I have a print a the colors in array in <select><option>
});
On clicking the button I would like to create a <select>
tag with all the colours in the array, populated with the <option>
's background colour being the value of the colour.单击按钮时,我想创建一个
<select>
标记,其中包含数组中的所有颜色,并填充<option>
的背景颜色作为颜色值。
I am not sure how I could proceed.我不确定如何继续。 All I know is it can be done using jQuery as the array is dynamic.
我所知道的是它可以使用 jQuery 来完成,因为数组是动态的。 Thanks in advance.
提前致谢。
You can do it using .map()
function of the array.您可以使用数组的
.map()
函数来完成。 Use this way:使用这种方式:
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); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id="button1">Click</button> <div></div>
If you want the <select>
to change the background colour based on the <option>
, then you can do this:如果您希望
<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()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id="button1">Click</button> <div></div>
I suggest other solution with plain JavaScript.我建议使用纯 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"); };
<button id="button">Click me</button> <div id="box"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.