【问题标题】:Is there a way to give HTML elements unique IDs for using a for loop to create them in JavaScript?有没有办法为 HTML 元素提供唯一的 ID,以便使用 for 循环在 JavaScript 中创建它们?
【发布时间】:2019-04-05 01:24:40
【问题描述】:

我正在创建几个 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>`;
}

【问题讨论】:

  • 你为什么认为你需要一个 id?
  • 您可以随时将i 的值附加到countrylist 的id 值
  • id=countrylist${i} 但确实不需要 id....
  • document.getElementById("locations").innerHTML += 对性能非常不利,而且还有其他副作用。

标签: javascript html node.js json dom


【解决方案1】:

你是这个意思吗?

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);
}
&lt;div id="locations"&gt;&lt;/div&gt;

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

【讨论】:

    【解决方案2】:

    您可以在每个按钮中添加 i 的值,它会有所不同,因为它每次都会更改为新按钮。

    for(let i=0;(i<5)&&(i<10); i++){
        document.getElementById("locations").innerHTML += "<button type='button' id=countrylist-"+i+" class='list-group-item list-group-item-action'>test</button>";
        console.log('Button with id countrylist-'+i+' has been added.');
    }
    &lt;div id="locations"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案3】:

      当然,您已经在使用模板文字,因此您可以像设置按钮文本一样设置 id。

      `<button id=${countryJSON[i].id}>${countryJSON[i].name}</button>`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 2020-09-28
        • 1970-01-01
        • 2016-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多