为了简单的示例起见:我想更改下拉列表中每个选项的背景颜色。每个选项应具有与其值对应的背景色。
例如。
$('...').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和本机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