最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add class to option in select - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked Apr 22, 2011 at 9:30 user472285user472285 2,6745 gold badges38 silver badges55 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 9

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

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

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

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

Easiest way to add class to an option:

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

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

.rubrique option[value="2"]{
     background: yellow;
}
发布评论

评论列表(0)

  1. 暂无评论