首页 > 解决方案 > 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')
    
        })
      })

标签: javascripthtmljquery

解决方案


您可以使用以下内容:

$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>


推荐阅读