如何使用javascript将大量的选择选项移动到另一个选择控件

How to move large amount of select options to another select control using javascript?

本文关键字:选择 选项 移动 另一个 控件 javascript 何使用      更新时间:2023-09-26

我在决斗列表框控件上方有一个链接,该控件为"全选"。功能是将<select>选项从一个选择移动到另一个选择。

jQuery从源移动到目标,运行良好,但现在源<select>中有超过100000条记录,并导致

未捕获范围错误:超出的最大调用堆栈大小

在Chrome中,在Firefox中弹出一个无响应的脚本。这是jQuery:

$('#' + source + ' option').remove().appendTo('#' + destination).removeAttr('selected');

有没有一种方法可以限制对浏览器的影响,而不会导致大量<option>出现问题?

我没有足够的声誉发表评论,但我想加入讨论。我似乎甚至无法构建一个可以使用jquery在googlechrome中打开的select语句。我的代码是

function selectBuild() {
html = '<select id="select1">';
for (i=0;i<100001;i++) {
    html += '<option>' + i + '</option>';
}
html += '</select>';
$('#selectdiv').html(html);
html ='';
}

也许您可以将所有选项迭代到一个数组并重新打印该数组?有点像

var options = new Array();
$('#'+source+' option').each(function() { options.push($(this).val()); });
html = '<select id="' + destination + '">';
$(options).each(function(index,value) { html+='<option>'+value+'</option>'; });
html += '</select>';
$('#div').html(html);

与其逐行解析,不如将整个HTML从源代码复制到目标代码,然后从源代码中删除HTML。我不完全确定你对活动类做了什么,但你可能只需要添加一个addClass()或removeClass()作为nessecary。

$('#' + destination).html($('#' + source + ' option').html());
$('#' + source + ' option').html('');

这里有一个jsFiddle和一个工作示例,尽管它没有100000个选项。https://jsfiddle.net/j9qtej9r/