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

Cra*_*aig 3 performance jquery selectedindex selected selector

我在一个包含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中是否有某些东西使得:当数字变得过高时,选择的选择器会如此慢?我想在我的脚本中坚持使用jquery,有没有人建议加快在jquery中找到所选的选项?

谢谢,

克雷格

ben*_*wey 10

获取选择框的val时无需调用:selected.

默认行为是获取selectedIndex

$( "#institutionCombo").val();
Run Code Online (Sandbox Code Playgroud)

如评论中所述,如果您需要访问该选项的文本,您可以使用

$( "#institutionCombo option[value=" + $( "#institutionCombo").val(); + "]").text();
Run Code Online (Sandbox Code Playgroud)

虽然如果您知道需要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()
Run Code Online (Sandbox Code Playgroud)

这是来自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;  
    // ...  
},
Run Code Online (Sandbox Code Playgroud)

当你调用:selected选择器时,将遍历所有选择元素后代,寻找要设置的.selected属性,并返回任何数组.无论哪种方式,你都会循环所有后代,所以不要这样做.