从js数组中获取select选项和值的最佳方式是什么

what is best way to get select options, values from js array

本文关键字:最佳 方式 是什么 选项 数组 js 获取 select      更新时间:2023-09-26

我正在尝试编写js,以便我的select选项下拉列表从我的数组中获取值和文本。js对我来说是新的。jsfiddle

我需要的值是数字和文本中的引号来自:

var locations = [
    [23, 'Main Room'],
    [1, 'Main Lobby'],
    [2, 'Training Room'],
    [56, 'Main Office'],
    [57, 'Lower Office'],
    [9, 'Lower Lobby'],
    [62, 'Conference Room'],
    [22, 'Outdoor Patio'],
    [63, 'Upper Lobby']
    ];
var select = document.getElementById("selectRoom");
for(var i = 0; i < locations.length; i++) {
    var opt = locations[i];
    var el = document.createElement("option");
    el.textContent = opt; // I just want the text within quotes from 
    el.value = opt; // I just want the number from opt
    select.appendChild(el);
}

或者我的数组应该看起来像?locations={"23":"主厅","1":"大堂"};

您的位置是包含两个元素的数组,您的值在索引0中,您的文本在索引1 中

for(var i = 0; i < locations.length; i++) {
    var opt = locations[i];
    var el = document.createElement("option");
    el.textContent = opt[1]; 
    el.value = opt[0];
    select.appendChild(el);
}

如果你想使用一个对象,这是更好的,然后按照@Hallvar的建议设置你的位置,我本来打算用他的相同答案进行编辑,但他打败了我。

快速修复,更改为:

el.textContent = opt[1]; // I just want the text within quotes from 
el.value = opt[0]; // I just want the number from opt

然而,正如你所想的,使用一个对象来实现这一点更为常见:

var locations = {
    23: 'Main Room',
    1: 'Main Lobby',
    2: 'Training Room',
    56: 'Main Office',
    57: 'Lower Office',
    9: 'Lower Lobby',
    62: 'Conference Room',
    22: 'Outdoor Patio',
    63: 'Upper Lobby'
    };
var select = document.getElementById("selectRoom");
for(var key in locations) {
    if(location.hasOwnProperty(key)) {
        var el = document.createElement("option");
        el.textContent = locations[key]; // I just want the text within quotes from 
        el.value = key; // I just want the number from opt
        select.appendChild(el);
    }
}

要从数组中获取值,必须使用文本的locations[i][0]locations[i][1]

你也可以使用Option构造函数来最小化你的代码

for(var i = 0; i < locations.length; i++) {
    var el = new Option(locations[i][1], locations[i][0]);
    select.appendChild(el);
    //select.add(el, null); I think there is an issue with add in IE
}