Javascript 从数组中填充下拉列表和 select 一些选项

Javascript fill dropdown from array and select some options

我想 select month[i][2] = "1" 的选项,可以有多个 selected.

function addOption_list() {
    var month = [["1", "January", ""], [["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]]

    var select = document.getElementById('select_table');
    for (var i=0; i < month.length;++i){
        var option = document.createElement("OPTION"),
            txt = document.createTextNode(month[i][1]);
        option.appendChild(txt);
        option.setAttribute("value",month[i][0]);
        if(month[i][2]!=''){
            // February need to be selected
            select.insertBefore(option,select.lastchild);
        } else {
            // others not
            select.insertBefore(option,select.lastchild);
        }
    }
}

将属性 multiple 添加到 select 元素,然后,当满足给定数组条目的条件时,将属性 selected 添加到相应的新创建的 option 像这样 option.setAttribute('selected', true);

function addOption_list() {
    var month = [["1", "August", "1"], ["1", "January", ""], ["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]];

    var select = document.getElementById('select_table');
    for (var i=0; i < month.length;++i){
        var option = document.createElement("OPTION"),
            txt = document.createTextNode(month[i][1]);
        option.appendChild(txt);
        option.setAttribute("value", month[i][0]);
        if(month[i][2] === '1'){
            option.setAttribute('selected', true);
            select.insertBefore(option, select.lastchild);
        } else {
            select.insertBefore(option,select.lastchild);
        }
    }
}

addOption_list();
<select multiple id="select_table"></select>

当您 运行 片段时,您会看到两个项目被选中,因为我已将 ["1", "August", "1"] 添加到列表中。

您可以稍微更改一下代码,使其更具可读性。

function addOption_list() {
  const month = [["1", "August", "1"], ["1", "January", ""], ["3", "Mars", ""], ["4", "April", ""], ["5", "May", ""], ["2", "February", "1"]];
  const select = document.getElementById('select_table');

  month.forEach(mnth => {
    const option = document.createElement('OPTION');
    option.textContent = mnth[1];
    if (mnth[2] === '1') { option.setAttribute('selected', true) };
    select.append(option);
  });
}

addOption_list();
<select multiple id="select_table"></select>