从Array或Object添加选项值和内部HTML

时间:2016-03-01 10:41:18

标签: javascript

我想知道使用JavaScript从数组中的每个项目创建新的HTML元素<option>的最佳方法(如果有更好的方法,可能不使用数组?

如何运行为数组中的每个项目创建新option的循环,然后将url指定为选项值。

Here is my current JS Fiddle.

我的JS如下:

    var images = [
  "Sports 1",
    "http://lorempixel.com/50/50/sports/1",
  "Sports 2",
    "http://lorempixel.com/50/50/sports/2",
  "Sports 3",
    "http://lorempixel.com/50/50/sports/3",
];

var index, len;
for (index = 0, len = images.length; index < len; index++) {
    var newoption = document.createElement('option');
    newoption.innerHTML = images[index];
    document.getElementById('imagelist').appendChild(newoption);
}

html应如下所示:

<form id="imageform">
  <select id="imagelist" name="imagelist">
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
    <option value="http://lorempixel.com/50/50/1">Sports 1</option>
  </select>
</form>

2 个答案:

答案 0 :(得分:1)

使用对象存储键值对。

final GradientBoostedTreesModel model = ...;
model.save(jsc.sc(), "some-path");

https://jsfiddle.net/Luyxqu75/2/

答案 1 :(得分:0)

  

而不是array,您应该array objects

试试这个:

var images = [{
  "key": "Sports 1",
  "value": "http://lorempixel.com/50/50/sports/1"
}, {
  "key": "Sports 2",
  "value": "http://lorempixel.com/50/50/sports/2"
}];

for (var index = 0, len = images.length; index < len; index++) {
  var newoption = document.createElement('option');
  newoption.value = images[index].value;
  newoption.innerHTML = images[index].key;
  document.getElementById('imagelist').appendChild(newoption);
}
<form id="imageform">
  <select id="imagelist" name="imagelist">
  </select>
</form>

Fiddle