简体   繁体   English

jQuery如何在选择中更改一个单词的颜色 <option>框

[英]Jquery how to change color of one word in select <option> box

Have select-option box with word Select and language names 具有带有单词选择和语言名称的选择选项框

If language name is not selected, then see word Select. 如果未选择语言名称,请参阅单词Select。

If I see word Select, on page load want to see the word Select in red color. 如果我看到“选择”一词,则在页面加载时希望看到红色的“选择”一词。

However it is not red. 但是它不是红色的。 If I click on the box and navigates to some language name, then word Select becomes red. 如果我单击该框并导航到某个语言名称,则“选择”字样将变为红色。 But I need it red if box is not clicked (on page load to pay user attention). 但是如果没有单击框,我需要将其设为红色(在页面加载时要引起用户注意)。

Here is example http://jsfiddle.net/z7264x9t/ 这是示例http://jsfiddle.net/z7264x9t/

And here is code 这是代码

<select name="language" id="language">
<option id="red_color">Select</option>
<option value="en">English</option>
<option value="ru">Русский</option>
<option value="lv">Latviešu</option>
</select>

jquery jQuery的

var language_check = $("#language").val();
if ( language_check == 'Select' ) {
$('#red_color').css('color', 'red');
}
else if ( language_check != 'Select' ) {
$('#red_color').css('color', 'green');
}

I suppose it is because red_color is id of <option> , not the word Select. 我想这是因为red_color<option> id,而不是单词Select。 But how to define id for the word Select? 但是,如何为“选择”一词定义ID?

Try using jQuery blur() 尝试使用jQuery blur()

DEMO DEMO

  $('#language').on('change',function(){
       $('#language').blur();
      $('#red_color').css('color', 'red');
    });

Reference : jQuery blur 参考: jQuery模糊

Try this: http://jsfiddle.net/z7264x9t/6/ 试试这个: http : //jsfiddle.net/z7264x9t/6/

   check();
function check(){
    var language_check = $("#language").val();
if ( language_check == 'Select' ) {
    $("#language").css({'border-color': 'red','color':'red'});
    $('#language option:first-child').css({'color':'red'});
    $('#language>option+option').css({'color':'black'});
}
else if ( language_check != 'Select' ) {
    $("#language").css({'border-color': 'black','color':'green'});
//    $("#language option:first-child").css({'color':'black'});
    $("#language option[value="+language_check+"]").css({'color':'green'});
}
}

$("#language").change(function(){
check();
});

Updated: http://jsfiddle.net/z7264x9t/6/ 更新时间: http : //jsfiddle.net/z7264x9t/6/

For example: 例如:

$('#language option').each(function(){
   if($(this).attr('value') == 'ru'){
      $(this).css('background-color', 'red');
   }
});

should work 应该管用

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

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