gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:33:24 25 4
gpt4 key购买 nike

我想知道使用 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>

最佳答案

使用对象来存储键值对。

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/

关于javascript - 从数组或对象添加选项值和内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35720712/

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