如何使用javascript仅更改选定选项的背景色?

如何使用javascript仅更改选定选项的背景色?,javascript,html,Javascript,Html,当用户选择某个选项时,我试图更改背景颜色。我使用onchange函数完成了此操作,该函数只包含: function colorSameValues(select, color){ for (var i=0; i<selects.length; i++){ if (selects[i].value ==='') selects[i].style.backgroundColor=''; if (selects[i].value === select.va

当用户选择某个选项时,我试图更改背景颜色。我使用onchange函数完成了此操作,该函数只包含:

function colorSameValues(select, color){
    for (var i=0; i<selects.length; i++){
        if (selects[i].value ==='') selects[i].style.backgroundColor='';
        if (selects[i].value === select.value) selects[i].style.backgroundColor=color;
    }
}
函数colorSameValues(选择,颜色){
对于(var i=0;i试试这个

$('button#first').on('click', function() {
  $('#mySelect option').attr('selected', false);  // clears all
  var options = [];
  for (var i=0; i < $('#mySelect optgroup[label="first"] option').length; i++){
    options.push($('#mySelect optgroup[label="first"] option')[i].value);
  };
  $('#mySelect').val(options);
  $("#mySelect").trigger("chosen:updated");       // updates chosen
  return false;                                   // returns false not to post the surrounding form
});
$('button#first')。在('click',function()上{
$('mySelect option').attr('selected',false);//清除所有
var期权=[];
对于(var i=0;i<$('#mySelect optgroup[label=“first”]option')。长度;i++){
options.push($('#mySelect optgroup[label=“first”]option')[i].value);
};
$('#mySelect').val(选项);
$(“#mySelect”).trigger(“已选择:已更新”);//已选择更新
return false;//返回false不发布周围的表单
});

您必须访问所选选项并更改背景

功能a(e)
{
e、 选项[e.selectedIndex].style.backgroundColor=e.options[e.selectedIndex].textContent;
console.log(e.options[e.selectedIndex].textContent)
}

红色
蓝色
绿色
像这样试试

我为
选项添加了一个css
background。在JS中,我为选择框设置了背景

函数changeColor(colorParam){
让color=colorParam.value.toLowerCase();
var optionElement=document.getElementById('rgb');
optionElement.style.background=颜色;
};
选项{
背景:#fff;
}

红色
绿色
蓝色
白色
粉红色

你能添加你的代码来看看你到底在做什么吗?我编辑了我的问题,并把一些代码与我想得到的图片放在一起。这不完全是我想要的,请看一看我编辑的问题-我标记了我想着色的选项这不完全是我想要的,请看一看我编辑的问题-我想我想要的颜色是什么