我有一个很好的双重选择框,并想知道什么是删除所有选项并包含新选项的最有效方法。这是我目前的方法(也欢迎jQuery-less建议):
var citiesSelect = $('#cities'),
cities = ['A bunch', 'Of', 'Cities'], //would come from an external array of AJAX
option;
citiesSelect.find('option').each(function() {
$(this).remove();
});
cities.unshift('---'); //including a blank option
for (i in cities) {
option = document.createElement('option');
option.value = i;
option.innerText = cities[i];
citiesSelect.append(option);
}
This is the JSPerf that resulted from this question(这已被隐藏在答案的评论中)。
答案 0 :(得分:1)
使用以下内容可以提高效率。这是一个你可以摆弄的小提琴 http://jsfiddle.net/NqRrB/。我还创建了一个jsperf,您也可以添加测试:http://jsperf.com/for-vs-for-in-stack。
var citiesSelect = $('#cities'),
cities = ['A bunch', 'Of', 'Cities'], //would come from an external array of AJAX
option;
citiesSelect.empty();
cities.unshift('---'); //including a blank option
for (var i = 0;i < cities.length; i++){
option = document.createElement('option');
option.value = i;
option.innerText = cities[i];
citiesSelect.append(option);
}
答案 1 :(得分:1)
这有点短,执行起来可能更快:
var citiesSelect = $('#cities'),
cities = ['A bunch', 'Of', 'Cities']; // would come from an external array of AJAX
citiesSelect[0].options.length=0; // clear existing options
cities.unshift('---'); // including a blank option
// populate with new options:
$(cities).each(function(i,v){
citiesSelect.append(new Option(v, i));
});
使用本机dom有时比使用jQuery更简单,更快捷。 特别是 options 集合和 Option()构造函数非常适合管理选择。
答案 2 :(得分:1)
一次添加大量dom元素的最有效方法之一是使用文档片段。 MDN
var citiesSelect = $('#cities'),
cities = ['A bunch', 'Of', 'Cities'], //would come from an external array of AJAX
option,
frag = document.createDocumentFragment();
citiesSelect.empty();
cities.unshift('---'); //including a blank option
for (var i = 0;i < cities.length; i++){
option = document.createElement('option');
option.value = i;
option.innerText = cities[i];
frag.appendChild(option);
}
citiesSelect.append(frag);
我还在@Jack的jsperf https://stackoverflow.com/users/680420/jack
中添加了一个测试用例这是一个Fiddle