将课程添加到下拉选项 [英] Add class to dropdown option

查看:50
本文介绍了将课程添加到下拉选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的html代码

<select class="input"  id="shopperlanguage" name="shopperlanguage">
<option selected="" value="ja_JP">日本語</option>
<option value="en">English (International)</option>
</select>

我想向每个选项添加两个类,例如,如果值是ja_JP,则需要添加japImg类,如果值是en,则需要向该选项添加engImg类.值是默认设置,我无法通过jquery或java脚本访问需要执行的代码.

I want to add two classes to each option like when if value is ja_JP then need to add japImg class and if value is en need to add engImg class to that option. value is by default set and i can not access the code i need to do it by jquery or java script.

我尝试过此代码,但是仅当我从下拉列表中选择ja_JP选项时,它才添加类.我需要添加它而不选择下拉菜单,只需检查option的值并添加该类即可.

I have tried this code but its adding classes only when i select ja_JP option from dropdown. I need to add it without selecting drop down menu just check value of option and add that class.

<script  type="text/javascript">
 var e = document.getElementById("shopperlanguage"); 
 var strUser = e.options[e.selectedIndex].value;
 if(strUser=="ja_JP"){
 $("#shopperlanguage").find("option").addClass("japimg");
 </script>

此代码被添加仅当选择含有选项值Ja_JP表示类.我只需要通过检查选项值来添加类.我可以像任何条件一样使用CSS来检查选项值并添加CSS规则吗?

this code is adding class only when that option containing value ja_JP is selected. I need to add classes just by checking the option value.Can i do this using css like any condition is css to check option value and add css rules?

推荐答案

更新
更简单,更快捷的解决方案:

update
even simpler and faster solution:

$("#shopperlanguage option[value='ja_JP']").addClass("japimg");

(您在这里不需要 find ,因为您只需使用正确的选择器就可以过滤所有内容)

( you don't need find here, cause you can filter it all just with the right selector )

旧答案

忘记其他的javascript代码行.只需使用它来查找具有特定值的选项:

forget your other lines of javascript-code. simply use this to find options with a specific value:

 $("#shopperlanguage").find("option[value='ja_JP']").addClass("japimg");

编辑:正在运行 JSFiddle

加号::根据需要使用 option -值不是一个好习惯.它使下拉列表的样式取决于该值,在您的情况下,这可能是您所需要的.在其他情况下,您可能希望将值与样式分开.请参阅我的第二个示例以了解替代解决方案.


第二个示例
使用 data 属性 html :

plus: it isn't good practice to use the option-value for your needs. it makes the style of your dropdown depending on the value, which in your case could accidently be what you want. in other cases you might want to separate the values from your style. see my 2nd example for an alternative solution.


2nd example
using a data attribute, html:

<select class="input" id="shopperlanguage" name="shopperlanguage">
    <option value="en">English (International)</option>
    <option selected="" value="ja_JP" data-red="1">日本語</option>
    <option value="en" data-red="1">English (International)</option>
    <option selected="" value="ja_JP">日本語</option>
</select>

javascript 部分:

 $("#shopperlanguage").find("option[data-red=1]").addClass("japimg");

和:用于数据属性示例的JSFiddle

这篇关于将课程添加到下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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