如何加快 jquery :selected 选择器的速度?

2024-02-27

我的网页中有一个下拉列表,其中包含 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 中是否有继承的东西使得 :selected 选择器在数字太高时变得如此缓慢?我想在我的脚本中始终坚持使用 jquery,有没有人建议加快在 jquery 中查找所选选项的速度?

Thanks,

Craig


获取选择框的值时无需调用 :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 属性,并将返回一个包含任何元素的数组。无论哪种方式,它都会循环所有后代,所以不要这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何加快 jquery :selected 选择器的速度? 的相关文章

随机推荐