动态设置选择元素的选项会跳过第一个元素
我动态构建了一个分为两个选项组的选项数组。这些选项组存储在名为 ogs
的 JavaScript 数组中。其代码如下:
var ogs = [];
for (optGroup in optionsList) {
var og = document.createElement('optgroup');
og.label = optGroup;
var ops = optionsList[optGroup];
for (op in ops) {
var o = document.createElement('option');
o.value = op;
o.text = ops[op];
og.appendChild(o);
}
ogs.push(og);
}
现在,我尝试将这些选项添加到 2 个选择元素,如下所示:
var from_el = document.getElementById('from_selector'), to_el = document.getElementById('to_selector');
for (i = 0; i < ogs.length; ++i) {
var og = ogs[i];
from_el.add(og);
to_el.add(og);
}
但是,在脚本末尾,只有 to_selector
填充了选项,而 from_selector
保持为空。我填充这样的选项的原因是因为这两个 select 元素都使用 select2,而任何其他方法(例如 innerHTML
)都会花费更长的时间。我还尝试将这些选择器放入数组中并迭代它们,总是填充最后一个选择,而第一个选择保持为空。
I've dynamically built an options array divided in two options group. These options groups are stored in a javascript array named ogs
. The code for the same is as below:
var ogs = [];
for (optGroup in optionsList) {
var og = document.createElement('optgroup');
og.label = optGroup;
var ops = optionsList[optGroup];
for (op in ops) {
var o = document.createElement('option');
o.value = op;
o.text = ops[op];
og.appendChild(o);
}
ogs.push(og);
}
Now, I'm trying to add these options to 2 select elements, as below:
var from_el = document.getElementById('from_selector'), to_el = document.getElementById('to_selector');
for (i = 0; i < ogs.length; ++i) {
var og = ogs[i];
from_el.add(og);
to_el.add(og);
}
However, at the end of the script, only to_selector
has the options populated, whereas from_selector
remains empty. The reason I'm populating the options like this is because both these select elements use select2, and any other method (such as innerHTML
) is taking significantly longer. I've also tried putting these selectors in array and iterating over them, always the last select gets populated, whereas first select remains empty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
弄清楚了问题。问题出在以下几行:
当 og 添加到 to_el 时,它与 from_el 分离。解决方案是将其替换为。
Figured out the issue. The problem was in the following lines:
When og was getting added to to_el, it was getting detached from from_el. The solution was to replace this with.