如何使用JAVASCRIPT将BUTTON添加到每个HTML表行中



我创建了一个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>

最新更新