gpt4 book ai didi

javascript - 有没有办法为 HTML 元素提供唯一的 ID,以便使用 for 循环在 JavaScript 中创建它们?

转载 作者:行者123 更新时间:2023-12-02 23:53:41 25 4
gpt4 key购买 nike

我正在创建几个 HTML 按钮来充当列表,它们都被添加到具有 id 'locations' 的同一个按钮中。每个按钮可以有不同的 id。

我可以将变量指定为 id 而不是字符串吗?

for(let i=0;(i<countryJSON.length)&&(i<10); i++){
document.getElementById("locations").innerHTML += `<button type='button' id=countrylist class="list-group-item list-group-item-action">${countryJSON[i].name}</button>`;
}

最佳答案

你的意思是这样的吗?

const countryJSON = [
{ name: 'one' }, { name: 'two' }, { name: 'three' },
];

const locations = document.getElementById('locations');

for(let i = 0; i < countryJSON.length && i < 10; i++) {
const btn = document.createElement('button');

btn.id = `location${i}`;
btn.className = 'list-group-item list-group-item-action';
btn.innerHTML = countryJSON[i].name;

locations.appendChild(btn);
}
<div id="locations"></div>

在这种情况下,每个按钮都有自己唯一的 ID,例如 location0location1 等。

关于javascript - 有没有办法为 HTML 元素提供唯一的 ID,以便使用 for 循环在 JavaScript 中创建它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521551/

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