如何提高jquery:selected选择器的速度?
我在一个包含3830个元素的网页上有一个下拉列表。我知道,但不管怎样 在jquery中,我使用以下语句获取所选选项值: $institutionCombo:selected.val 在找到所选内容之前,会出现明显的停顿。一旦我得到这个值,我就把它插入页面上的文本框中,这样我就知道有多快了。另外,我在Firebug中使用断点检查了它 如果我走老路,使用以下javascript: var div=document.getElementById maindiv; var select=div.getElementsByTagName select[0]; var ix=select.selectedIndex; var instit=select.options[ix].value 这个速度是瞬间的 在jquery中是否有什么东西会使:selected选择器在数字过高时变得如此缓慢?我想在我的脚本中始终坚持使用jquery,有人建议加快在jquery中查找所选选项的速度吗 谢谢 克雷格你可以这样做: var ix=$institutionCombo.attr selectedIndex var值=$institutionCombo选项:eq+ix+.val 但是,这实际上就是你在旧校规中所做的 我很惊讶有明显的延迟,因为我会认为我在上面所做的就是jQuery代码为:selected选择器所做的 否则,我想知道是否是语法错误导致了延迟,您可能应该这样做 $institutionCombo选项:选中.val如何提高jquery:selected选择器的速度?,jquery,performance,selector,selected,selectedindex,Jquery,Performance,Selector,Selected,Selectedindex,我在一个包含3830个元素的网页上有一个下拉列表。我知道,但不管怎样 在jquery中,我使用以下语句获取所选选项值: $institutionCombo:selected.val 在找到所选内容之前,会出现明显的停顿。一旦我得到这个值,我就把它插入页面上的文本框中,这样我就知道有多快了。另外,我在Firebug中使用断点检查了它 如果我走老路,使用以下javascript: var div=document.getElementById maindiv; var select=div.getE
注意选项:selected vs:selected获取选择框的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选择器时,该选择器将在所有select元素中循环,查找要设置的.selected属性,并将返回任意值的数组。无论采用哪种方式,它都会循环所有的Decedent,所以不要这样做。啊,糟了,已经有五个标签了。我很想给这个贴上标签,你完蛋了,或者只是wtf3830…这是一个笑话,谁能滚动这么多…你不滚动,你只需开始键入,下拉菜单就会找到最接近的匹配项。这比如果你只有一个列表框,那么你就必须滚动要容易得多。事实上,没有用户抱怨选择太多,因为它很容易使用。很抱歉,办公室断电,无法响应。这很好,但听起来如果你想得到所选的文本,你仍然必须回到朱利安所说的老派方法。还是有一个我不知道的jquery方法也能做到这一点?回答了这个问题-使用var v=$institutionCombo.val;var t=$institutionCombo[value='+v+'].text;