动态设置选择元素的选项会跳过第一个元素

发布于 2025-01-13 06:57:17 字数 911 浏览 1 评论 0原文

我动态构建了一个分为两个选项组的选项数组。这些选项组存储在名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情何以堪。 2025-01-20 06:57:17

弄清楚了问题。问题出在以下几行:

from_el.add(og);
to_el.add(og);

当 og 添加到 to_el 时,它与 from_el 分离。解决方案是将其替换为。

from_el.add(og);
to_el.add(og.cloneNode(true));

Figured out the issue. The problem was in the following lines:

from_el.add(og);
to_el.add(og);

When og was getting added to to_el, it was getting detached from from_el. The solution was to replace this with.

from_el.add(og);
to_el.add(og.cloneNode(true));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文