如何加速jquery:选择的选择器?

我在一个包含3830个元素的网页中有一个下拉列表。 我知道,过分但无论如何。

在jquery中,我使用以下语句获取所选的选项值:

$(“#institutionCombo:selected”)。val();

在找到选择之前有一个明显的暂停。 一旦我得到了这个值,我就把它插入到页面的文本框中,所以我知道它有多快。 另外,我在Firebug中使用断点检查了它。

如果我去上学并使用这个javascript:

var div = document.getElementById(“maindiv”);
var select = div.getElementsByTagName(“select”)[0];
var ix = select.selectedIndex;
var instId = select.options [ix] .value;

这种速度是瞬间的。

在jquery中是否有一些inheritance使得:当数字变得过高时,选择的选择器会如此慢? 我想在我的脚本中坚持使用jquery,有没有人建议加快在jquery中找到所选的选项?

谢谢,

克雷格

获取选择框的val时无需调用: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选择器时,将遍历所有选择元素后代,寻找要设置的.selected属性,并返回任何数组。 无论哪种方式,你都会循环所有后代,所以不要这样做。

你可以这样做:

var ix = $(“#institutionCombo”)。attr(“selectedIndex”);

var value = $(“#institutionCombo option:eq(”+ ix +“)”)。val();

但是,这实际上是你在老派代码中所做的。

我很惊讶有一个明显的延迟,因为我会认为我正在做的是jQuery代码正在为:selected选择器做的事情。

否则,我想知道是否是导致延迟的语法错误,你可能应该这样做

$(“#institutionCombo option:selected”)。val();

(注意选项:选中vs:已选中)