繁体   English   中英

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

[英]How to add a BUTTON in to each HTML table rows using JAVASCRIPT

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

并且为按钮分配了一个 class ,您可以通过 class 引用此按钮:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM