首页 > 解决方案 > 如何使用 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>

标签: javascripthtml

解决方案


在我的示例中,使用了该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>


推荐阅读