繁体   English   中英

从数组中填充Javascript并选择一些选项

[英]Javascript fill dropdown from array and select some options

我要选择其中month[i][2] = "1" ,可以选择多个选项。

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); 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM