设置< select> < option>中的颜色颜色 [英] setting <select> color from <option> color

查看:392
本文介绍了设置< select> < option>中的颜色颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从标签的颜色设置标签的文本颜色

hi i would like to set text color of tag from color of tag

HTML

<select class="widocznosc">
    <option value="prywatna" class="note_0">prywatna</option>
    <option value="publiczna" class="note_2">publiczna</option>
    <option value="tylko dla grupy" class="note_16">tylko dla grupy</option>
</select>

CSS

.note_0
{
    color: #b59285;
}
.note_2
{
    color: #e7511e;
}
.note_16
{
    color: #6a89a5;
}

jQuery

jQuery("select.widocznosc").change(function(){
        jQuery(this).css("color", jQuery(this).children("option:selected").css("color")); 
    });

这在我更改选项时有效,但是我想在页面加载之前设置颜色,然后再进行任何更改

this works when i'm changing options, but i want set color when page loads before any changings

请帮助我

推荐答案

您可以执行以下操作:

jQuery("select.widocznosc").change(function(){
        jQuery(this).css("color", jQuery(this).children("option:selected").css("color")); 
    }).change();

请注意最后添加的.change().这意味着,首先在下拉菜单上设置change处理程序,然后立即调用它.

Note the added .change() at the end. This means that first you set a change handler on the dropdown, then you immediately call it.

注意:这将触发与这些下拉列表相关联的每个事件处理程序.

Note: This will trigger every event handler you have associated with these dropdowns.

我几乎忘记了演示.

更新:请注意,您可以像这样重写代码,以避免不必要的jQuery()调用(虽然性能有所提高,但是对于更干净的代码,这也是一种最佳做法):

UPDATE: Please note that you could rewrite your code like this to avoid unnecessary jQuery() calls (small performance gains, but it is considered a best practice also for cleaner code):

jQuery("select.widocznosc").change(function(){
    var $this=jQuery(this);
    $this.css("color", $this.children("option:selected").css("color")); 
}).change();

jQuery(this)的结果保存到局部变量中,然后使用它代替多次调用该函数.您可以使用任何变量名,我只是使用$this来表示它存储了一个jQuery集合(这就是$的原因).

You save the result of jQuery(this) into a local variable and you use that instead of calling the function several time. You can use any variable name, I just used $this to indicate that it stores a jQuery collection (that's why the $).

这篇关于设置&lt; select&gt; &lt; option&gt;中的颜色颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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