javascript - 通过行点击事件传递动态创建的 html 表格行内文 ID
问题描述
我有一个htmltable
动态创建的。我已使行可点击。我需要将行内部文本 id 传递给单击该行时触发的脚本。
htmltable
:
<table style="width:100%;">
<tr>
<th>id</th>
<th>name</th>
<th>other info</th>
</tr>
<tr>
<td class='table_row_click'>11</td>
<td class='table_row_click'>item 2</td>
<td class='table_row_click'>lmfao</td>
</tr>
<tr>
<td class='table_row_click'>22</td>
<td class='table_row_click'>item 2</td>
<td class='table_row_click'>lol</td>
</tr>
</table>
点击事件:
$(document).ready(function ($) {
$(".table_row_click").click(function (e) {
//I need to use the clicked row ID here for something
});
});
解决方案
$(e.target).closest('tr').find('td').first().text();
您可以向上导航到父 tr,找到 td 元素,获取第一个元素,然后获取其文本。
closest('tr')
如果类在 td 或 tr 级别,则using将起作用,因为closest()
可以匹配自身。
推荐阅读
- database - Flutter 应用程序的最佳数据库设置是什么?
- android - 我放置在线性布局中的搜索项目,其中包含 Android 搜索上的按钮自定义文本
- angular - 如何使用 Angular Cli v11 为库构建 esm5 构建?
- cassandra - cassandra中的Commons Collections漏洞
- elasticsearch - 当存在品牌术语匹配时搜索产品索引并优先考虑结果
- java - Java Stream - 创建排序重复的映射
- azure - 如何安全地自动将多个设备连接到 IoT Central?
- storyboard - 板视图与 Sprint 视图
- apache-spark - SparkContext stop() 未结束驱动程序 pod - 未调用关闭挂钩
- pug - 条件输入取决于 Pug 中的单选框?