javascript - 使用 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方法,但它也不起作用。
解决方案
当您发表评论时,您不知道如何使用 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>
推荐阅读
- scala - 直接引用内部案例类中的值或方法
- javascript - 如何在 JavaScript 中匹配二维数组中的对?
- python - 如何在数字所在的确切位置裁剪图像?
- java - 我的反向 LinkedList 程序出了什么问题,导致堆栈溢出错误。
- r - 删除 R 中的假负值
- pandas - 熊猫将值更改为 nan
- gradle - 如何使用 Gradle Kotlin DSL 为 FatJar 指定入口点 Main-Class?
- node.js - Nginx 反向代理 + ExpressJS + Angular + SSL 配置问题
- javascript - 使用 JQuery 将弹出窗口附加到页面后,如何在弹出窗口中播放 gif?
- java - Java 8 Wildfly 14 OutOfMemoryError 阶段安装