javascript - Html Table按单元格值获取行ID
问题描述
我想通过搜索单元格值从表中获取行 ID 或索引,但我不知道如何。请帮助我开始!:)
<button id="button" class="btn btn-secondary">Get index of row 2</button>
<table id="table">
<tbody>
<tr data-index="0">
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
<tr data-index="1">
<td>cell 4</td>
<td>cell 5</td>
<td>cell 6</td>
</tr>
<tr data-index="2">
<td>cell 7</td>
<td>cell 8</td>
<td>cell 9</td>
</tr>
</tbody>
</table>
var $table = $('#table')
var $button = $('#button')
var $SearchFor ='cell 5'
$(function() {
$button.click(function () {
alert('row id of '+$SearchFor+' is')
})
})
解决方案
您可以使用以下内容:
$table.find("td:contains('"+$SearchFor+"')").parent().index();
或者
$table.find("td:contains('"+$SearchFor+"')").parent().data("index");
演示
var $table = $('#table')
var $button = $('#button')
var $SearchFor = 'cell 5'
$(function() {
$button.click(function() {
var i = $table.find("td:contains('"+$SearchFor+"')").parent().index();
console.log($SearchFor + " is found in row with data-index " +i)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button" class="btn btn-secondary">Get index of row 2</button>
<table id="table">
<tbody>
<tr data-index="0">
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
<tr data-index="1">
<td>cell 4</td>
<td>cell 5</td>
<td>cell 6</td>
</tr>
<tr data-index="2">
<td>cell 7</td>
<td>cell 8</td>
<td>cell 9</td>
</tr>
</tbody>
</table>
推荐阅读
- kubernetes - kubespray openstack terraform“错误:找不到模块”错误
- excel - 在多个工作表中查找并替换具有唯一标识符的列中的值
- python - 如何设置微调器值等于kivy中python方法的输出列表
- c# - 正确的 DI 或服务定位器反模式?
- apache - 如何打印所有活动的 httpd 配置参数?
- amazon-web-services - 为什么我应该使用 IAM 角色?
- docker - Docker-compose 多个端口暴露
- python - matplotlib geopandas 用颜色方案的设置箱绘制叶绿素
- mongodb - 由于 src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp 365 处的致命断言 28558,MongoDB docker 构建失败
- sql - match_recognize 是否可以选择保留所有原始行并标记匹配项?