我如何可以加快jQuery的:选定的选择?
-
23-08-2019 - |
题
我有一个网页与它3830个元素下拉。我知道,过度但不管。
在jquery的我得到使用语句选择的选项值:
$( “#institutionCombo:选择了”).VAL();
找到该选择之前有一个明显的暂停。一旦我得到这个值我将其插入到页面上的文本框,所以我知道有多快。另外,我一直在使用断点在Firebug它选中。
如果我去老同学和使用此JavaScript的:
变种的div =的document.getElementById( “maindiv”);结果 VAR选择= div.getElementsByTagName( “选择”)[0];结果 VAR = IX select.selectedIndex;结果 VAR instId = select.options [Ⅸ]。价值;
此速度instananeous。
有jQuery的继承这是令:选择选择这么慢如果这些数字是否太高?我想用jQuery坚持在整个我的剧本,没有任何人有一个建议,以加快寻找在jQuery中所选择的选项?
谢谢,
克雷格
解决方案
有不需要调用:得到一个选择框的VAL时选择
。的默认行为是得到的selectedIndex
$( "#institutionCombo").val();
正如评论指出的那样,如果你需要访问该选项的文本可以使用
$( "#institutionCombo option[value=" + $( "#institutionCombo").val(); + "]").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;
// ...
},
当调用:这是要遍历所有选择元素decendents寻找要设置的.selected属性和将返回的任何一个阵列选择选择器。无论哪种方式,你这样做,将循环中的所有decendents,所以不这样做。
其他提示
您可以这样做:
变种IX = $( “#institutionCombo”).attr( “的selectedIndex”);
VAR值= $( “#institutionCombo选项:当量(” + 1X + “)”).VAL();
不过,这是有效的,你在你的旧学校代码做什么。
我很惊讶,有一个显着的延迟,因为我本来认为正是我上面做的是什么jQuery代码是做为:选择的选择
否则,我不知道它是延误了一个语法错误,你应该做
$( “#institutionCombo选项:选择了”).VAL();
(注选项:选择VS:选择的)