gpt4 book ai didi

javascript - 选择插件: Change the background of options depending on its value

转载 作者:行者123 更新时间:2023-12-02 18:23:19 25 4
gpt4 key购买 nike

为了简单的示例:我想更改下拉列表中每个选项的背景颜色。每个选项都应该有一个与其值相对应的背景颜色。

例如

$('...').css('background', 'red')

我尝试选择 .active-result,但它不起作用。

有什么想法吗?

$(function() {

var $select = $(document.getElementById('foo')),
colors = ['red', 'yellow', 'green', 'purple', 'silver']
;

for(var i = 0; i < 5; i++) {
$select[0].add(new Option('Color: ' + colors[i], colors[i]));
}

$select[0].options[2].selected = true;

$select.chosen();

});

Link to jsbin

最佳答案

那么,您想设置元素的颜色吗?尝试在创建它们并将它们添加到 <select> 时执行此操作。 .

另外,您有 jQuery,请使用它!不要混合使用 jQuery 和 native DOM 方法。

$(function(){
var $select = $('#foo'), // Don't use getElementById
colors = ['red', 'yellow', 'green', 'purple', 'silver'];

for(var i = 0, len = colors.length; i < len; i++){ // Don't hard-code the length
var $option = $('<option></option>', { // jQuery can create elements
text: 'Color: ' + colors[i],
value: colors[i]
}).css('background-color', colors[i]); // set the color

$select.append($option); // Append the element using jQuery
}

$select.val(colors[2]); // jQuery can also set the "selected" option

$select.chosen();
});

演示:http://jsbin.com/otASETo/3

关于javascript - 选择插件: Change the background of options depending on its value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com