在JQuery中设置选择选项的背景颜色 [英] Setting background-color of select options in JQuery

查看:130
本文介绍了在JQuery中设置选择选项的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个选择框的页面,如下所示:

 < select name =item-0 -statusid =id_item-0-status> 
< option value => ---------< / option>
< option value =1>在线< / option>
< option value =2>离线< / option>
< option value =3>未知< / option>
< / select>

这些是在django中自动生成的,因此不可能应用css类,id或属性直接到选项。 select元素具有'item-0-status','item-1-status','item-2-status'等id。

如何添加css颜色到使用select元素的id的选项?



我试图在这里遵循代码:如何在jQuery中的SELECT元素中选择特定选项?



这导致我做,例如以下将离线选项设置为红色:

  $('select [id $ =  -  status] [id ^ = id_item  - ]')。children()。find('option [value =2]')css('background-color','#FF0000'); 

但这没有效果。



如何使这项工作?我实现支持这一点在浏览器之间有所不同,但这不是一个问题。对于这个问题的工作在Firefox 3.6就够了。

解决方案

有点像应该工作, 。

  $(function(){

$('#id_item-0-status') .children()。(
function(){
if($(this).val()== 2){
$(this).css 'red'});
}
}
);

})


I have a page with multiple select boxes, as per the following:

<select name="item-0-status" id="id_item-0-status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>

These are being auto-generated in django, so it is not possible to apply css classes, ids or attributes directly to the options. The select elements have ids of 'item-0-status','item-1-status','item-2-status' etc.

How can I add css colours to the options using the id of the select element?

I have tried to follow the code here: How do you select a particular option in a SELECT element in jQuery?

This has lead me to do, e.g. the following for setting 'offline' options to red:

$('select[id$=-status][id^=id_item-]').children().find('option[value="2"]').css('background-color','#FF0000');

but this has no effect.

How can I make this work? I realise support for this varies between browsers, but this is not an issue. For the purposes of this question working in Firefox 3.6 is enough.

解决方案

Something like should work though note that I am not so sure.

$(function(){   

$('#id_item-0-status').children().each(
        function (){
            if($(this).val() == 2){
                $(this).css({'background':'red'});
            }
        }
);

})  

这篇关于在JQuery中设置选择选项的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆