首页 > 解决方案 > 使用 vanilla javascript 在 HTML 表格行中动态添加按钮

问题描述

我从 API 接收 JSON 数据,并使用 vanilla javascript 将此数据填充到 HTML 表中。我正在尝试在每一行的末尾动态添加一个按钮来执行某些功能,但我还没有找到方法。这是我用数据填充表的函数


const showArtist = (data) => {
  let tableStructure = `<table>
        <thead>
          <tr>
           <th>Sr#</th>
           <th>Name</th>
           <th>Country</th>
           <th>Disambiguation</th>
           <th>Info</th>
          </tr>
        </thead>
          <tbody id="tbody"></tbody>
        </table>
      `;
  artistTable.innerHTML = tableStructure;
  let tableBody = document.getElementById("tbody");
  for (let i = 0; i < Object.keys(data).length; i++) {
    let tr = "";

    tr += `<tr>
            <td>${i}</td>
            <td>${data[i].name}</td>
            <td>${data[i].country}</td>
            <td>${data[i].disambiguation}</td>

            <td><input type="button" value="" >Add</input></td>
          </tr>`;
    tableBody.innerHTML += tr;
  }
};

我曾尝试使用appendChild方法,但它也不起作用。

标签: javascripthtmlhtml-table

解决方案


当您发表评论时,您不知道如何使用 appendChild,我将答案留在这里。

下面的例子

const artistTable = document.querySelector("#artistTable");

const data = [
  {
    name: "a",
    country: "bbb",
    disambiguation: "cc",
  },
  {
    name: "sss",
    country: "eeee",
    disambiguation: "dddddd",
  },
];

const showArtist = data => {
  let tableStructure = `<table>
        <thead>
          <tr>
           <th>Sr#</th>
           <th>Name</th>
           <th>Country</th>
           <th>Disambiguation</th>
           <th>Info</th>
          </tr>
        </thead>
        <tbody id="tbody"></tbody>
        </table>
      `;
  artistTable.innerHTML = tableStructure;
  let tableBody = document.getElementById("tbody");
  for (let i = 0; i < Object.keys(data).length; i++) {
    const tr = document.createElement("tr");
    tr.innerHTML = `<td>${i}</td>
    <td>${data[i].name}</td>
    <td>${data[i].country}</td>
    <td>${data[i].disambiguation}</td>
    <td><input type="button" value="" >Add</input></td>
   `;
    tableBody.appendChild(tr);
  }
};

showArtist(data);
<div id="artistTable"></div>


推荐阅读