首页 > 解决方案 > 连接按钮以使用 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>

标签: javascripthtml

解决方案


下面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将始终设置为最后一次迭代值。


推荐阅读