javascript - 连接按钮以使用 Javascript 在 html 表中显示数据

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

关于javascript - 连接按钮以使用 Javascript 在 html 表中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57567095/

相关文章:

javascript - 如何从background.js中的当前选项卡获取文档

html - IE11 中 div 之间的 1px 间距

javascript - 如何找到元素的位置并将其应用于不同的元素?

javascript - 函数单独工作但不能组合在一起

javascript - 使用 Javascript 变量作为 EJS 数组的索引 - NODEJS

javascript - 使用 php session 的事件 session 中菜单列表的方法

javascript - 在 angularjs 1.0.8 中不起作用 PUT 休息服务

html - &lt;!DOCTYPE html> 删除媒体查询样式

javascript - 如何仅使用日期选择器获取日期年月日

html - 如何在有 Angular Material 中将 Logo 居中对齐?