根据所选选项的类别更改选择的类别 [英] Change select's class based on selected option's class

查看:71
本文介绍了根据所选选项的类别更改选择的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中包含许多< select>元素.我试图实现的是确保如果< select>的selected< option>有一个名为 italic 的类,则< select>然后添加了 italic 类(即jQuery.addClass('italic')).如果不是,则将 italic 类从< select>中删除.以确保其他< option>元素正确显示(即jQuery.removeClass('italic')).

I have a page that contains numerous <select> elements. What I'm trying to achieve is to ensure that if a <select>'s selected <option> has a class called italic, then the <select> then has the italic class added (i.e. jQuery.addClass('italic')). If it doesn't, then the italic class is removed from the <select> to ensure other <option> elements are displayed correctly (i.e. jQuery.removeClass('italic')).

我在大多数尝试中注意到的是,所有< select>具有 italic 类,或者没有相应地删除 italic 类.

What I'm noticing with most of my attempts is that either all the <select> have the italic class or that the italic class isn't being removed accordingly.

由于我不确定选择器的选择和回调逻辑在这种情况下是否特别有效(因为我一直在努力使其工作),因此我决定不包括先前使用的代码尝试.相反,请参考此小型HTML& CSS示例:

Since I'm unsure my choice in selectors and callback logic are particularly sound or good practice in this instance (as I've been frustratingly trying to make it work) I've decided not to include the code I used in previous attempts. Instead, refer to this small HTML & CSS example:


.italic {
    font-style: italic;
}

<select id="foo" name="foo" size="1">
  <option value="NA" selected="selected"> - Select - </option>
  <option value="1">Bar</option>
  <option value="2">Fu</option>
  <option value="3">Baz</option>
</select>

此外,我知道并不是所有的浏览器都支持< select>的CSS样式.和< option>.相关的J2EE Web应用程序只能在受控环境下通过Firefox进行访问.

Also, I am aware that not all browsers support CSS styling of <select> and <option>. The related J2EE web application will only ever be accessed via Firefox under a controlled environment.

推荐答案

如果用户更改了您选择的"foo"中的选项,则函数将根据所选选项应用或删除斜体.

In case user changes option in your select "foo", function will apply or remove italic based on the selected option.

$("select").change(function(e) {
    var select = e.target;
    var option = select.options[select.selectedIndex];
    if ($(option).hasClass('italic')) {
        $(select).addClass('italic');
    } else {
        $(select).removeClass('italic');
    }
});

这篇关于根据所选选项的类别更改选择的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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