Javascript 将类添加到选择中的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5754114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:43:08  来源:igfitidea点击:

add class to option in select

javascriptjquery

提问by user472285

Based on the value of an option would that be possible to add a class to an option?

基于一个选项的值,是否可以将一个类添加到一个选项中?

So if i have this:

所以如果我有这个:

   <select class="rubrique" name="ctl00">
    <option value="" selected="selected"></option>
    <option value="1">1</option>
    <option value="1">1</option>
    </select>

i'll get that:

我会明白的:

<select class="rubrique" name="ctl00">
        <option class="" value="" selected="selected"></option>
        <option class="1" value="1">1</option>
        <option class="2" value="1">1</option>
        </select>

回答by lonesomeday

Yes, very easily, using the callback signature of addClass:

是的,很容易,使用回调签名addClass

$('.rubrique option').addClass(function() {
    return this.value;
});

回答by Damb

$('.rubrique > option').each(function(){
    $(this).addClass($(this).val());
});

Edit: I am not sure if .val() is 100% correct here, you could also use this:

编辑:我不确定 .val() 在这里是否 100% 正确,你也可以使用这个:

$('.rubrique > option').each(function(){
    $(this).addClass($(this).attr('value'));
});

回答by cptstarling

If it's the purpose to style a particular option element, you could consider this approach as well:

如果目的是为特定选项元素设置样式,您也可以考虑这种方法:

.rubrique option[value="2"]{
     background: yellow;
}

回答by Rohil Patel

Easiest way to add class to an option..

将类添加到选项的最简单方法..

$("#IdOfSelect option[value='" + valueOfSelect + "']").addClass('hidden');

$("#IdOfSelect option[value='" + valueOfSelect + "']").addClass('hidden');