gpt4 book ai didi

javascript - 如何使用 JAVASCRIPT 在每个 HTML 表格行中添加按钮

转载 作者:行者123 更新时间:2023-12-03 08:30:59 29 4
gpt4 key购买 nike

我创建了一个 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() 方法创建的:

let button = document.createElement('button');

接下来,将创建第 th 标记来放置按钮:

let td = document.createElement('td');

并且为该按钮分配了一个类,通过该类可以通过类来引用该按钮:

button.className = 'btn_buy';

使用此代码,将为所有表格行创建一个按钮!

let tr = document.querySelectorAll("table tbody tr");

Array.from(tr).forEach(function(trArray) {
let button = document.createElement("button");
let td = document.createElement("td");
button.innerText = "buy";
button.className = "btn_buy";
td.append(button);
trArray.append(td);
});
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>

<tbody>
<tr>
<td>Soap</td>
<td>good for babies</td>
<td>75</td>
</tr>

<tr>
<td>Milk</td>
<td>manufactured</td>
<td>100</td>
</tr>

<tr>
<td>Rice</td>
<td>red rice 1kg pack</td>
<td>130</td>
</tr>
</tbody>
</table>

关于javascript - 如何使用 JAVASCRIPT 在每个 HTML 表格行中添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65112372/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com