获取选择框的值时无需调用 :selected 。
默认行为是获取 selectedIndex
$( "#institutionCombo").val();
正如评论中所述,如果您需要访问该选项的文本,您可以使用
$( "#institutionCombo option[value=" + $( "#institutionCombo").val(); + "]").text();
尽管如果您知道需要 text 属性并且它与值不同,您可能只想直接使用 selectedIndex 。
var combo = $("#institutionCombo").get(0);
combo = combo ? combo : {selectedIndex: -1}; // handle no combo returned
if (combo.selectedIndex < 0)
return; // nothing selected
$('#institutionCombo option:eq(' + combo.selectedIndex + ')').text()
这是 jquery 源代码 (v1.3) 的片段
val: function( value ) {
// ...
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type == "select-one";
// Nothing was selected
if ( index < 0 )
return null;
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
// Get the specifc value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one )
return value;
// Multi-Selects return an array
values.push( value );
}
}
return values;
// ...
},
当您调用 :selected 选择器时,它将循环遍历所有 select 元素的后代,寻找要设置的 .selected 属性,并将返回一个包含任何元素的数组。无论哪种方式,它都会循环所有后代,所以不要这样做。