gpt4 book ai didi

javascript - 从 js 数组中获取选择选项和值的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-30 08:50:56 24 4
gpt4 key购买 nike

我正在尝试编写 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": "Main Room", "1": "Main Lobby"};

最佳答案

你的位置是有两个元素的数组,你的值在索引 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 的建议设置您的位置,我打算用他的相同答案进行编辑,但他抢先一步

关于javascript - 从 js 数组中获取选择选项和值的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17955884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com