选择的插件:根据其值更改选项的背景

时间:2013-09-04 14:52:18

标签: javascript jquery

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

E.g。

$('...').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

1 个答案:

答案 0 :(得分:2)

那么,你想设置元素的颜色吗?尝试在创建它们时将其添加到<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();
});

DEMO:http://jsbin.com/otASETo/3