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

标签 javascript jquery

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

例如

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

相关文章:

javascript - 解析时 JSON 输入意外结束

javascript - 为什么我的 jQuery 没有返回 <select> 的值

jquery - 在标签jquery中解决html img标签

javascript - 不同浏览器中日期值的 JSON.stringify 差异

javascript - 按下时应显示所有具有类的元素

javascript - 是否有可能在 Protractor 中使用 cssContainingText 获取下一个 sibling

javascript - Webpack 提取 SASS SCSS 到 js 或 json 文件

javascript - jqGrid - 内联编辑时选择选定单元格的文本

javascript - 以最少的浪费为 k 个人切 n 个蛋糕

javascript - Fancybox 无法在 IE 中工作 : object doesn't support this method