2011-06-01 91 views
9

我知道如何使用jquery獲取元素的屬性。但我不確定如何使用選擇字段中的實際選項來執行此操作。jquery查找選擇選項屬性

<select referenceID="55" name="test" id="test"> 
    <option value="1">first option</option> 
    <option value="2">second option</option> 
    <option value="3">third option</option> 
</select> 

爲了得到referenceID我只是這樣做:

$("#test").attr("referenceID"); 

當我想要得到的值:

$("#test").val(); 

但我希望得到一個更有趣一點。我想提出一些具體的信息到每個選項:

<select name="test" id="test"> 
    <option value="1" title="something here"*>first option</option> 
    <option value="2" title="something else here">second option</option> 
    <option value="3" title="another thing here">third option</option> 
</select> 

是否有可能搶在選項標籤中的屬性?

我打算有一個讀取標題標籤的onselect函數,並幫助我處理其他一些事情。

回答

16

假設你想找到所選選項的title屬性...

$('#test option:selected').attr('title'); 

也就是說,找到#test後代元素是(A)的選項元素和(b)is selected

如果你們已經包含#test一個選擇,你可以用find做到這一點:

$('#test').find('option:selected').attr('title'); 
+0

大非常感謝 – 2014-10-01 06:05:01

0

這難道不是工作?如果你使用的onchange

$("#test").change(function() { 

    var title = $(this).attr("title"); 

}); 
1

,您可以使用下面這樣的:

$("#test").change(function(){ 
    var title = $(this).find('option:selected').attr('title'); 
});