javascript - 连接按钮以使用 Javascript 在 html 表中显示数据
问题描述
我有一个使用 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
将始终设置为最后一次迭代值。
推荐阅读
- api - 如何在快递中手动注册基于分类的路线
- c++ - 如何在内核 C 的控制台/视频(受保护)模式下伪造我的操作系统适配屏幕?
- c - 使用 Cython 以 void 指针作为参数包装 C 函数
- python-3.x - 熊猫 iloc 返回空结果
- python - 在 Tkinter 的文本框中保存和重新打开数据
- ansible - 当我运行我的 Ansible-Playbook 时,我希望我的任务名称专门执行
- assembly - 将寄存器设置为 1 的首选方法
- javascript - 如何添加 JavaScript 警报消息以显示使用 JavaScript 的 html 表单验证是正确的
- reactjs - 组件颜色的初始渲染问题
- javascript - Javascript:尽管条件为真,但如果语句未执行,并且要执行的代码在 If 之外工作