动态添加9000个选项以在JavaScript中选择在IE上花费太长时间 [英] Adding 9000 options dynamically to select in javascript taking too long on IE

查看:167
本文介绍了动态添加9000个选项以在JavaScript中选择在IE上花费太长时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人帮助我创建优化代码以便动态添加9000多个选项以选择框,我将不胜感激。基本上,为了简化每个选项,我将文本和值都作为for循环的索引。



我已经尝试了许多选项,例如:


  1. 为所有9000条记录一次创建选项元素字符串,然后使用jquery和纯javascript添加到选择元素中



<2>

  for循环{
options [options.length] = new Option (文本,值);
}

然后:

  selectElement.options.add(选项); 



<3> 3。

  var objOption = document.createElement(option); 
objOption.value = value;
objOption.text = text;
htmlElement.options.add(objOption);

这些片段几乎都是同一时间。有什么方法可以在2-3秒内完成?

解决方案

好吧,你说你已经尝试添加字符串说实话,9000选项相当多。我建议使用诸如精选的之类的东西,以增加这种巨大选择的可用性。 / p>

无论如何,我试图以简单的方式修改选择,并且工作得非常快。

检查 jsFiddle



它的功能是使用 html() jQuery方法将选项添加为字符串。

  //插入
的选项数量var noptions = 9000;

//当前选项的数量
var nOpts = $('#huge_select option')。length;

//当前选项html
var options = $('#huge_select')。html();
for(var i = 0; i< noptions; ++ i){
//将html选项添加到当前集合
options + =< option value =' +(1 + nOpts)+ '> 中+(1 + nOpts)+ < /选项> 中;
}
//设置select html
$('#huge_select')。html(options);


I would appreciate if somebody helps me creating optimized code for adding 9000+ options dynamically to select box. Basically for simplicity for every option I am keeping text and value both as index of for loop.

I have tried many options like:

  1. Creating option element string at once for all 9000 records and then adding to select element using both jquery and plain javascript

2.

for loop { 
    options[options.length] = new Option(text, value);
} 

and then:

selectElement.options.add(options);

3 .

var objOption = document.createElement("option");
objOption.value = value;
objOption.text = text;
htmlElement.options.add(objOption);

These all snippets are taking almost same time. Is there any way to finish this up in 2-3 seconds?

解决方案

Well, you say you have tried to add the string and, to be honest, 9000 options are quite a lot. I would suggest using something like chosen-select in order to increase usability for such a huge select.

Anyway, I've tried to modify the select in a plain way and it works pretty fast.

Check this jsFiddle.

What it does is to add the options as a string using the html() jQuery method.

// number of options to insert
var noptions = 9000;

// number of current options
var nOpts = $('#huge_select option').length;

// current options html
var options = $('#huge_select').html();
for (var i = 0; i < noptions; ++i) {
    // add the html options to the current set
    options += "<option value='"+(i+nOpts)+"'>"+(i+nOpts)+"</option>";
}
// set the select html
$('#huge_select').html(options);

这篇关于动态添加9000个选项以在JavaScript中选择在IE上花费太长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆