1

我正在尝试编写 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);
}

或者我的阵列应该是什么样子?位置= {“23”:“主房间”,“1”:“主大厅”};

4

3 回答 3

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 的建议设置你的位置,我打算用他相同的答案进行编辑,但他打败了我

于 2013-07-30T19:40:20.707 回答
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);
    }
}
于 2013-07-30T19:45:37.320 回答
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
}
于 2013-07-30T19:49:44.317 回答