使用原版 javascript 在 HTML table 行中动态添加按钮

Add a button dynamically in a HTML table row using vanilla javascript

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

填充 table 的函数

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 方法,但它也不起作用。

替换此行:

tableBody.innerHTML += 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>`;
const parser = new DOMParser(),
doc = parser.parseFromString(tr, "text/html");
tableBody.appendChild(doc.querySelector('tr'))

这应该有效。

更简洁的解决方案是使用 document.createElement()document.cloneNode()document.appendChild() 的组合。 做一些像

// Before for loop create tr and td element.
const tr = document.createElement('tr');
const td = document.createElement('td');

// Then inside for loop, Instead of using string definition,

let row = tr.cloneNode(true)
// Repeat these steps to create all <td>:
td1 = td.cloneNode(true);
td1.innerText = i // value
row.appendChld(td1) // Add all td to tr
tbody.appendChild(row)

如您评论您不知道如何使用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>