javascript - 在 TypeScript 中获取表格行索引和行数据
问题描述
我有一个 HTML 表格,其创建方式如下:
<table id="tableID" onclick="getRowData()" class="table table-hover"></table>
起初,它会填充一些初始数据,这可能使其看起来像这样:
From Action To
a 1 b
a 0 a
我希望能够从任意行中检索数据,只需单击网页上的该行。我也希望能够从该行中检索行索引。例如,如果我想从第一行获取数据,那么我会得到a 1 b
这样的功能会是什么样子?
解决方案
您必须将点击处理程序放在行上,而不是放在桌子上。
由于您的表格是动态生成的,因此从 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');
推荐阅读
- java - 从 JTree 获取 CustomObject 的嵌套列表,包括叶子
- python - Tensorflow:如何在 4D 数据格式(如(batch_size、width、hight、channels)上使用 1D/2D 算子,保留 batch_size 和 channels
- sql - 带有 Cosmos DB 的文档字段的参数化输入
- laravel - 为什么 Laravel 在 SQL 查询中会报错?
- c# - 如何使用 Xamarin.Forms 中的绑定启用多选列表视图的开关?
- java - 为我的 java 游戏渲染不同层中的对象的有效方法是什么
- c++ - 如何使用 Valgrind 确定“仍然可用”内存泄漏的来源?
- wpf - 我安装的 WPF 应用程序在尝试创建文件时崩溃
- android - RxJava 有条件地从 Single 中返回 Maybe
或 Maybe.empty() - windows - windows minikube kubectl 无法拉取镜像