繁体   English   中英

HTML 动态表行未获取动态 ID

[英]HTML dynamic table row is not getting dynamic id

我有一个动态 HTML 表,当有新用户注册时,它会创建一个新行。 现在我正在尝试为该行提供一个带有 for 循环的 id,但它们都得到相同的 id,即:tableID99。 这是我的代码:

for (var i = 0; i < 100; i++) {
        row.id = "tableID" + i
      }

看起来表格不知道它是动态的还是什么的。 当我 console.log(row.id) 它是一个带有 tableID1 -> tableID1 -> tableID2 等的升序列表。我在这里缺少什么?

编辑:

function showTable() {
  // dummy data to start with
  let localStorageData = JSON.parse(localStorage.getItem("users"))

 
  // get button and table with query selector
  let createTable = document.querySelector("#table")

  // table heading
  let headers = ["ID", "Gebruikersnaam", "Email", "Wachtwoord", "Gebruikersrol", "Voornaam", "Achternaam", "Geboortedatum", "Adres", "Huisnummer", "Postcode", "Plaatsnaam", "Land", "Suspended"]


  // create table elements   
  let table = document.createElement("table");
  let headerRow = document.createElement("tr");
  
  // start loop 
  headers.forEach(headerText => {
    // create table heading and textnode    
    let header = document.createElement("th");
    let textNode = document.createTextNode(headerText);
    // append to DOM   
    header.appendChild(textNode);
    headerRow.appendChild(header);
    table.appendChild(headerRow)
  });


  // create loop that makes table
  localStorageData.forEach(localStorageData => {
    blokkeerButtons()
    // create table row    
    let row = document.createElement("tr");

    // create loop that set data in cells

    Object.values(localStorageData).forEach(localStorageData => {

      // create element and textnode      
      let cell = document.createElement("td");
      let textNode = document.createTextNode(localStorageData as string);

      // append to DOM   
      cell.appendChild(textNode);
      row.appendChild(cell);
      for (var i = 0; i < 100; i++) {
        row.id = "tableID" + i
        console.log(row.id)
    
      }
    });

    // append to DOM   
    table.appendChild(row);

  });
  // append to DOM   
  createTable.appendChild(table);

}

在此处输入图像描述

看起来您的代码中有 3 个循环来创建表:localStorateData.foreach、Object.values(localStorageData).forEach,以及从 0 到 99 的 for 循环。

您正在最外层循环中创建一个新行。 在最里面的 for 循环中,您所做的就是将新行的 id 重置 100 次。

考虑改成这样:

// create loop that makes table
var rowCount = 0;
localStorageData.forEach(localStorageData => {
  blokkeerButtons()
  // create table row    
  let row = document.createElement("tr");

  // create loop that set data in cells

  Object.values(localStorageData).forEach(localStorageData => {

    // create element and textnode      
    let cell = document.createElement("td");
    let textNode = document.createTextNode(localStorageData as string);

    // append to DOM   
    cell.appendChild(textNode);
    row.appendChild(cell);
  });

  // append to DOM
  row.id = "tableID" + rowCount;
  rowCount++;   
  table.appendChild(row);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM