[英]How to make first column's every row clickable to get data from that whole row? JavaScript
我正在尝试使表格的第一列的每一行(在本例中为订单 ID)可点击,以便我可以在我网站的另一个容器中显示来自该特定订单 ID 的更多信息。 我遍历了一些 JSON 数据来创建这样的表:
function printData(jsonData) {
let myTable = document.getElementById("jsonTable")
for(let i=0; i < jsonData.length; i++) {
let row = `<tr>
<td>${jsonData[i].orderid}</td>
<td>${jsonData[i].customerid}</td>
<td>${jsonData[i].customer}</td>
<td>${jsonData[i].invaddr}</td>
<td>${jsonData[i].delivaddr}</td>
<td>${jsonData[i].deliverydate}</td>
<td>${jsonData[i].respsalesperson}</td></tr>`
jsonTable.innerHTML += row
}
}
这就是我的 HTML 文件的样子:
<div class="datatable">
<div class="datatablecontent">
<table class="jsontable">
<tr id="jsontr">
<th>Order ID</th>
<th>Customer ID</th>
<th>Customer</th>
<th>InvAddr</th>
<th>Delivery Address</th>
<th>Delivery Date</th>
<th>Resp. For Sale </th>
<tbody id="jsonTable">
</tbody>
</tr>
</table>
</div>
</div>
在遍历jsonData
时,您可以在事件侦听器中声明回调。
因为您使用的是模板文字,所以我保持简洁并传递行索引。 您还可以通过在 JS 中添加事件侦听器来传递数据本身,为此您需要访问该元素。
function logRowData(index) { console.log(jsonData[index]) } let jsonData = [ {orderid: 0, customerid:14, customer: 'abc'}, {orderid: 1, customerid:25, customer: 'xyz'} ] printData(jsonData) function printData(jsonData) { let myTable = document.getElementById("jsonTable") for(let i=0; i < jsonData.length; i++) { let row = `<tr> <td onclick={logRowData(${i})}>${jsonData[i].orderid}</td> <td>${jsonData[i].customerid}</td> <td>${jsonData[i].customer}</td></tr>` jsonTable.innerHTML += row } }
<div class="datatable"> <div class="datatablecontent"> <table class="jsontable"> <tr id="jsontr"> <th>Order ID</th> <th>Customer ID</th> <th>Customer</th> <tbody id="jsonTable"> </tbody> </tr> </table> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.