javascript - 如何使用 JAVASCRIPT 在每个 HTML 表格行中添加一个 BUTTON
问题描述
我创建了一个 HTML 表格,如下所示。我需要在每个产品的价格后添加一个按钮。如何使用 JAVASCRIPT 做到这一点?(例如:假设表格有超过 20 行。我需要在每一行都有一个按钮)
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<th>Soap</th>
<th>good for babies</th>
<th>75</th>
</tr>
<tr>
<th>Milk</th>
<th>manufactured</th>
<th>100</th>
</tr>
<tr>
<th>Rice</th>
<th>red rice 1kg pack</th>
<th>130</th>
</tr>
</tbody>
</table>
解决方案
在我的示例中,使用了该forEach
方法。并且按钮也是使用以下createElement()
方法创建的:
var button = document.createElement('button');
接下来,th
将创建一个标签来放置按钮:
var th = document.createElement('th');
并且为按钮分配了一个类,您可以使用它按类引用该按钮:
button.className = 'btn_buy';
使用此代码,将为所有表格行创建一个按钮!
window.onload = function() {
var tr = document.querySelectorAll('#productTable tbody tr');
Array.from(tr).forEach(function(trArray, index) {
var button = document.createElement('button');
var th = document.createElement('th');
button.innerText = 'buy';
button.className = 'btn_buy';
th.append(button);
tr[index].append(th);
});
}
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<th>Soap</th>
<th>good for babies</th>
<th>75</th>
</tr>
<tr>
<th>Milk</th>
<th>manufactured</th>
<th>100</th>
</tr>
<tr>
<th>Rice</th>
<th>red rice 1kg pack</th>
<th>130</th>
</tr>
</tbody>
</table>
推荐阅读
- database - 从一个数据库调用初始化多个类
- docusignapi - Docusign 的 RequestJWTUserToken 方法中 ClientId 和 impersonatedUserId(UUID) 的参数在哪里获取?
- python - python - 如何替换数组中高于python上限或低于下限的数字?
- python - 在 DAG 中使用 boto3 时,Apache 气流无法找到 AWS 凭证
- ios - Swift Mjpeg 流仅显示单帧
- sql - 如果用户 ID 引用到某个表,则获取已删除的用户详细信息
- javascript - 在本机反应中正确导入组件?
- javascript - React useEffect中带有边界框的内存泄漏
- python - Python如何修复由于睡眠功能而导致的Tkinter窗口崩溃
- django - 如何在再次执行函数之前计算新数据