我有一个很好的'n'old 双选框,想知道删除所有选项并包含新选项的最有效方法是什么。这是我目前的方法(也欢迎不使用 jQuery 的建议):
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 (隐藏在答案的评论中)。
最佳答案
一次添加大量 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
关于javascript - 重新填充选择框的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390623/