我有一个使用 JS 对象数组的动态生成的表。我还在每一行上添加了“查看详细信息”。我需要的是能够在不同的表中显示来自同一对象数组的数据。
我尝试向按钮添加事件监听器,但它们要么遍历所有行,要么不显示任何内容
function drawTable(tbody) {
var tr, td;
tbody = document.getElementById(tbody);
for (var i = 0; i < products.length; i++) // loop through data source
{
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].ProductName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].UnitsInStock;
td = tr.insertCell(tr.cells.length);
// View Details button
td = tr.insertCell(tr.cells.length);
button = document.createElement('button');
button.textContent = ('View Details')
td.appendChild(button)
}
}
<div class="table-wrapper">
<table id="display-table" class="fl-table">
<thead>
<tr>
<th>Product Name</th>
<th>Units In Stock</th>
<th>View Details</th>
</tr>
</thead>
<tbody id="table-data">
</tbody>
</table>
</div>
<h2>Product Details</h2>
<div class="table-wrapper">
<table class="fl-table">
<thead>
<tr>
<th>Product Name</th>
<th>Product Category</th>
<th>Product Description</th>
</tr>
</thead>
<tbody id="table-details">
</tbody>
</table>
</div>
最佳答案
在button.textContent = ('View Details')
下面添加
button.onclick = (n=> event=> {
console.log('click on', products[n]) // you handler here
})(i); // set current loop "i" as parameter "n" value
我们将函数 event=>...
包装在 n=>...
中以传递当前 i
值 - 没有这个 i
将始终设置为最后一次迭代值。
关于javascript - 连接按钮以使用 Javascript 在 html 表中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57567095/