从js数组中获取select选项和值的最佳方式是什么
what is best way to get select options, values from js array
我正在尝试编写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
}
相关文章:
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 为react组件传递道具的最佳方式
- 让Webpack管理Quirky AMD定义的最佳方式
- 在承诺链中处理早期回报的最佳方式
- 在ng重复循环中显示条件内容的最佳方式是什么
- 在phonegap中为android调用onload函数的最佳方式
- 链接两个网页或网络应用程序的最佳方式
- 什么's是连接供应商js文件的最佳方式
- 什么's是在javascript中迭代项的最佳方式
- 在node.js中编写单元测试的最佳方式是什么
- 在页面上记录数据并实现pushstate()的最佳方式
- 使用AJAX在Rails中提交动态表单的最佳方式是什么
- 什么'这是加载jQuery的最佳方式
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 在网站上显示.mov作为加载屏幕的最佳方式
- 使用Angular存储用户以前是否选中过复选框,然后再调用它的最佳方式是什么
- 以角度渲染表中数据的最佳方式
- 删除集合中旧邮件/帖子的最佳方式
- 显示全屏Ajax加载程序的最佳方式
- PHP和JS中表单验证的最佳方式