在 TypeScript 中,可以通过以下步骤来实现通过单击表格中的按钮获取动态表格行数据:
<div id="tableContainer">
<table id="dataTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>john@example.com</td>
<td><button class="getDataBtn">Get Data</button></td>
</tr>
<tr>
<td>Jane Smith</td>
<td>jane@example.com</td>
<td><button class="getDataBtn">Get Data</button></td>
</tr>
<!-- 更多表格行 -->
</tbody>
</table>
</div>
// 获取表格和按钮的引用
const table = document.getElementById('dataTable') as HTMLTableElement;
const buttons = document.getElementsByClassName('getDataBtn');
// 为按钮添加点击事件监听器
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
// 获取所在行的数据
const row = this.parentNode.parentNode as HTMLTableRowElement;
const name = row.cells[0].innerText;
const email = row.cells[1].innerText;
// 处理数据
console.log('Name:', name);
console.log('Email:', email);
// 其他操作...
});
}
在上述代码中,我们首先通过 getElementById
方法获取表格的引用,并通过 getElementsByClassName
方法获取所有的按钮引用。然后,使用 addEventListener
方法为每个按钮添加点击事件监听器。在点击事件处理程序中,我们使用 parentNode
属性获取按钮所在行的引用,并通过 cells
属性获取每个单元格的引用。最后,我们可以根据需要处理获取到的数据。
这是一个简单的示例,你可以根据实际需求进行扩展和优化。如果你想了解更多 TypeScript 的相关知识和用法,可以参考腾讯云的 TypeScript 文档:TypeScript 文档。
领取专属 10元无门槛券
手把手带您无忧上云