繁体   English   中英

使用 vanilla javascript 在 HTML 表行中动态添加按钮

[英]Add a button dynamically in a HTML table row using vanilla javascript

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


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

当您发表评论时,您不知道如何使用 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>

替换这一行:

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)

暂无
暂无

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

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