2013-11-25 31 views
0
<select name="/static/images/legends/default.png" class="legend-icon"> 
    <option class="legend-icon" name="/static/images/legends/icon1.png">option1</option> 
    <option class="legend-icon" name="/static/images/legends/icon2.png">option2</option> 
    <option class="legend-icon" name="/static/images/legends/icon3.png">option3</option> 
</select> 

當組合框的值發生變化時,我想要新選擇的選項'name'。這是可能做到的嗎?如果是,如何?我試過這個:如何在'option'標籤上獲得'name'屬性

$('select').change(function(e) { 
    alert(e.delegateTarget.name); 
}); 

這會提醒'select'標籤的'名稱'。但我需要「選項」標籤的名稱。任何幫助?

+2

這不是有效的標記,並且無論您選擇何種方法都無法正常工作。 'options'沒有'name'屬性(來源:http://www.w3.org/TR/html-markup/option.html),即使他們這樣做了,你也會濫用它來使用它附上一些不是名字的東西。考慮一個數據屬性,而不是:'選項類=「傳奇 - 圖標」數據圖標=「/靜態圖像/傳說/ icon3.png」>選項3'。 – meagar

+0

感謝您的信息... – Praveen

回答

2

你需要找到所選擇的選項,然後找到它的名稱屬性值

$('select').change(function (e) { 
    alert($(this).find(':selected').attr('name')); 
}); 

演示:Fiddle

+0

感謝它的工作。但是它在'事件'對象中不可用嗎? – Praveen

+0

@Praveen否select事件由select元素觸發 –

2

這裏有一個解決方案:

http://jsfiddle.net/HLYYB/

$('select').change(function(e) { 
    console.log($('option:selected', this).attr('name')); 
}); 
2
$('select').change(function(e) { 
    console.log($(this).find('option:selected').attr('name')); 
}); 

http://jsfiddle.net/xZf42/

注:由於@meagar在他對你的問題發表評論時提及,name不是option元素的標準屬性。考慮使用以data-爲前綴的自定義屬性:

<option class="legend-icon" data-name="/static/images/legends/icon1.png"> 
    option1 
</option> 
相關問題