修改 select 中的单个选项并在不单击 select 的情况下显示更改

Modify a single option in a select and show changes without clicking into select

我有一个表格,其中包含一个 select 和几个 options。一个 option 可以根据数据库中的值默认 selected。

如果默认情况下 select 编辑了一个选项,我们希望对其应用一些样式。

呈现表单后,我可以简单地执行类似这样的操作...

$('#mySelect option:selected').addClass('customClass');

让我们说 customClass 只是 background-color:green.

加载表单后,select 中的选项仍默认为白色。单击 select.

后,它只会变成绿色

我认为这是因为只有选项被更改为绿色。 如果我这样做,只是 $('#mySelect').addClass('customClass'); 那么所有选项都是绿色的。

我考虑过将 class 应用于整个 select,然后遍历所有选项并删除 class 除了 selected 那个,但是那个好像效率不高。

有什么简洁的方法可以做到这一点吗?

谢谢!

这是一个简单的例子 almost working example

工作演示: https://jsfiddle.net/o81hyseg/

$("#mySelect").on("change", function(e){
    if(!e.isTrigger)
           $(this).find("option").removeAttr("selected");
      
   if($("#mySelect").val() == "green"){
      $('#mySelect').addClass('foo');
      $('#mySelect').attr('title', 'foo');
      $(this.options[this.options.selectedIndex]).attr("selected","");
   }
   else{
      $('#mySelect').removeClass('foo');
      $('#mySelect').removeAttr('title', 'foo');
   }
});

$("#mySelect").trigger("change");
.foo {
  background-color: green;
}

.foo option:not([selected]) {
  background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
  <option value="">Select...</option>
  <option>white</option>
  <option>white</option>
  <option>white</option>
  <option selected>green</option>
  <option>white</option>
 </select>