首页 > 解决方案 > 在 TypeScript 中获取表格行索引和行数据

问题描述

我有一个 HTML 表格,其创建方式如下:

<table id="tableID" onclick="getRowData()" class="table table-hover"></table>

起初,它会填充一些初始数据,这可能使其看起来像这样:

From  Action  To
 a      1     b
 a      0     a

我希望能够从任意行中检索数据,只需单击网页上的该行。我也希望能够从该行中检索行索引。例如,如果我想从第一行获取数据,那么我会得到a 1 b

这样的功能会是什么样子?

标签: javascripthtmltypescript

解决方案


您必须将点击处理程序放在行上,而不是放在桌子上。

由于您的表格是动态生成的,因此从 Typescript/JavaScript 附加点击处理程序可能更容易,这是一种方法。

用于document.querySelector('#tableID')获取对您的表的引用。

然后,有两种方法可以获取对表格行和单元格的引用:

  • 用于table.querySelectorAll('tbody td')查询表 DOM 中的行。然后用于row.querySelectorAll('td')获取细胞。

  • 使用表格 DOM API(请参阅下面的 @HB 评论)来避免查询每行和每个单元格的 DOM。使用这种技术,您可以获得带有 的行和带有table.tBodies[0].rows的单元格row.cells

然后使用element.addEventListener('click', handler)将点击处理程序附加到每一行。

这是一个带有详细注释的 JavaScript 演示:

// get a reference to your table by id
// cast this to HTMLTableElement in TypeScript
const table = document.querySelector('#tableID');

// get all rows in the first table body
const rows = table.tBodies[0].rows;

// convert the rows to an array with the spread operator (...)
// then iterate over each row using forEach
Array.from(rows).forEach((row, idx) => {
  // attach a click handler on each row
  row.addEventListener('click', event => {
    // get all cells in the row, convert them to an array with the spread operator (...)
    // then for each cell, return its textContent by mapping on the array
    const tds = Array.from(row.cells).map(td => td.textContent);

    console.clear();
    // Log the row index
    console.log('row index:', idx);
    // Log the tds content array
    console.log('tds content:', ...tds);
    // join the contents of the tds with a space and display the string
    console.log('tds string:', tds.join(' '));
  });
});
<table id="tableID">
  <thead>
    <tr><th>From</th><th>Action</th><th>To</th></tr>
  </thead>
  <tbody>
    <tr><td>a</td><td>1</td><td>b</td></tr>
    <tr><td>a</td><td>0</td><td>a</td></tr>
  </tbody>
</table>

此外,在您的 TypeScript 代码中,不要忘记将结果转换为document.querySelector('#tableID')toHTMLTableElement以获得正确的类型:

const table: HTMLTableElement = document.querySelector('#tableID');

查看 TypeScript 演示


推荐阅读