简体   繁体   English

更改背景颜色<option value="with JavaScript">与 JavaScript</option>

[英]Change the background color of an <option> with JavaScript

So, I know this seems a simple question but it's breaking my mind.所以,我知道这似乎是一个简单的问题,但它打破了我的想法。

I have a select menu我有一个 select 菜单

<select class="form-control" id="MYID">
<option value="">Selecione...</option>
<option selected="selected" value="1296">OPTION 1</option>
<option value="2313">OPTION 2</option>
<option value="-3">ADD NEW...</option>
</select>

That options value = -3 was added by the controller, so I can't edit with CSS.该选项值 = -3 是由 controller 添加的,因此我无法使用 CSS 进行编辑。 I wanted to put that option in a different background, using JS.我想使用 JS 将该选项放在不同的背景中。 So I tried getting the ID and then the value and then change the color所以我尝试获取 ID,然后获取值,然后更改颜色

var option = $('#MYID').val("-3");
option.style.color = "red";

I get: Cannot set property 'color' of undefined我得到:无法设置未定义的属性“颜色”

I only found answers to "change color to selected option" and that is not what I want.我只找到了“将颜色更改为所选选项”的答案,这不是我想要的。

That option appears in others dropdowns of the software and the value is always the same, so if there was a more general way to do it it would be awesome.该选项出现在软件的其他下拉列表中,并且值始终相同,因此如果有更通用的方法来做到这一点,那就太棒了。

So, thanks to @CBroe in the comments I found a way that is the best for me cause it's general.所以,感谢评论中的@CBroe,我找到了一种对我来说最好的方法,因为它是通用的。

Selects all elements with a value="-3" attribute:选择具有 value="-3" 属性的所有元素:

option[value="-3"] {
  background-color: red;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM