【问题标题】:Get table row index and row data in TypeScript在 TypeScript 中获取表格行索引和行数据
【发布时间】:2019-03-05 15:01:34
【问题描述】:

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

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

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

From  Action  To
 a      1     b
 a      0     a

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

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

【问题讨论】:

  • 表格元素中必须要有getRowData()吗?

标签: javascript html typescript


【解决方案1】:

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

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

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

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

  • 使用table.querySelectorAll('tbody td') 查询表 DOM 中的行。然后使用row.querySelectorAll('td') 获取单元格。

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

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

这是一个带有详细 cmets 的 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') 的结果转换为 HTMLTableElement 以获得正确的输入:

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

See the TypeScript demo

【讨论】:

  • 您可以使用表 DOM API,我更愿意始终查询。 IE。获取行 => table.tBodies[0].rows,获取单元格 => row.cells。 (在 TypeScript 中,您需要将第一个查询的结果转换为 HTMLTableElement。)
  • @H.B.,谢谢你的评论,你介意我更新我的答案吗?
  • 一点也不,继续。
  • @jo_va 当我尝试遵循您的代码示例时,当我尝试使用扩展运算符 [...rows] 时,我收到以下错误 type &lt;HTMLCollectionOf&lt;HTMLTableRowElement&gt; is not an array type。类型应该是什么?
  • @jo_va 非常感谢,我想我找到了错误。我的目标是 ES5 而不是 ES6。
猜你喜欢
  • 2018-04-23
  • 2012-11-14
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多