使用jQuery获取选择元素选项的值?

Pet*_*ter 3 jquery

我有以下HTML:

<div style="width: 143px; height: 125px; overflow: scroll;"><select size="20" style="min-width: 200px;" name="ctl00$ctl04$ctl00$ctl00$SelectResult" id="ctl00_m_g_ctl00_ctl00_SelectResult" multiple="multiple" title="selected values" onchange="GipSelectResultItems(ctl00_m_g_ctl00_MultiLookupPicker_m);" ondblclick="GipRemoveSelectedItems(ctl00_m_g_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m); return false" onkeydown="GipHandleHScroll(event)">
                <option value="14">BMT</option></select></div>
Run Code Online (Sandbox Code Playgroud)

无论价值是什么,我如何获得选项中的文本?我以为我可以这样做:

 var test = $('#ctl00_m_g_ctl00_ctl00_SelectResult selected:option').text(); 
Run Code Online (Sandbox Code Playgroud)

但它给了我"未定义".

有任何想法吗?

更新:如果select没有选项,我不想收到javascript错误.

Kar*_*ngu 5

请试试这个:

$('#ctl00_m_g_ctl00_ctl00_SelectResult option:selected').text();
Run Code Online (Sandbox Code Playgroud)

更新.为避免javascript错误,您可以使用以下内容:

var test = null;
var opt = $('#ctl00_m_g_ctl00_ctl00_SelectResult option:selected');

if (opt.length > 0){
  test = opt.text();
}
Run Code Online (Sandbox Code Playgroud)

然后检查测试是否为空.