获取所选选项的类名称

时间:2014-09-13 16:37:47

标签: jquery

我有一个非常像这样的选择标签

<select name="platform">
    <option class="one-test-one">one</option>
    <option class="two-test-two">two</option>
    <option class="three-test-three">three</option>
</select>
<div class="clickMe">click</div>

我正在尝试获取所选选项的class属性值。这就是我在jquery中所做的事情

$('.clickMe').on('click', function() {
    alert($('select[name="platform"]:selected').attr('class')); 
});

警报返回未定义..我做错了什么?

5 个答案:

答案 0 :(得分:5)

selected selector适用于option,不适用于select所以

$('select[name="platform"] :selected').attr('class')

演示:Fiddle

答案 1 :(得分:3)

<select name="platform">
<option class="one-test-one">one</option>
<option class="two-test-two">two</option>
<option class="three-test-three">three</option>
</select>
<div class="clickMe">click</div>




$('.clickMe').on('click', function() {
alert($('select[name="platform"] option:selected').attr('class')); 
});

check in fiddle: http://jsfiddle.net/ruapce/o11o1r6k/

答案 2 :(得分:1)

'selected'选择器适用于option中的select,请尝试以下操作: -

$('select[name="platform"] option:selected').attr('class');

编辑:

DEMO

答案 3 :(得分:0)

$('.clickMe').on('click', function() {
    alert($('select[name="platform"]').find(':selected').attr('class')); 
});

小提琴:http://jsfiddle.net/set1hdhy/

答案 4 :(得分:0)

试试这个我测试过它

$('.clickMe').on('click', function() {

   console.log($('select option:selected').attr('class')); 
});