什么是获取选择选项的最佳方法,来自js数组的值

时间:2013-07-30 19:38:27

标签: javascript arrays json

我正在尝试编写js,以便我的选择选项下拉列表从我的数组中获取值和文本。 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”:“主要大厅”};

3 个答案:

答案 0 :(得分:3)

您的位置是包含两个元素的数组,您的值在索引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建议,我打算用同样的答案编辑,但他打败了我

答案 1 :(得分:2)

快速修复,更改为:

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

答案 2 :(得分:0)

要从数组中获取值,您必须使用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
}
相关问题