为了简单的示例:我想更改下拉列表中每个选项的背景颜色。每个选项都应该有一个与其值相对应的背景颜色。
例如
$('...').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();
});
最佳答案
那么,您想设置元素的颜色吗?尝试在创建它们并将它们添加到 <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();
});
关于javascript - 选择插件: Change the background of options depending on its value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617112/