从数组或对象添加选项值和内部 HTML

Adding option values and inner HTML from an Array or Object

本文关键字:内部 HTML 选项 添加 数组 对象      更新时间:2023-09-26

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

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

这是我目前的JS小提琴。

我的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>

使用对象来存储键值对。

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;
var keys  = Object.keys(images);
for (index = 0, len = keys.length; index < len; index++) {
    var temp = keys[index];
    var newoption = new Option(temp, images[temp]);
    document.getElementById('imagelist').add(newoption);
}

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

与其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>

小提琴