在jQuery中获取表的行索引

Get row index of table in jQuery

本文关键字:索引 获取 jQuery      更新时间:2023-09-26

当用户单击一行时,我想获得下表中元素的索引。

    <table class="table table-hover" id="event_table">
    <thead>
      <tr>
        <th>Event Title</th>
        <th>Event Location</th>
        <th>Event Time</th>
        <th>Event Date</th>
      </tr>
    </thead>
    <tbody>
        <tr>
          <td>Gathering</td>
          <td>City Centre</td>
          <td>10:30</td>
          <td>10/09/2016</td>
        </tr>
        <tr>
          <td>Meetup</td>
          <td>Some place</td>
          <td>12:30</td>
          <td>15/09/2016</td>
        </tr>

    </tbody>
  </table>

我该如何使用jQuery?我尝试过类似的东西:

$("#event_table tbody tr").on("click", function() {
   $(this).index(); 
});

您的代码运行良好:

$("#event_table").on("click", "tbody tr", function() {
   alert($(this).index()); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table table-hover" id="event_table">
    <thead>
      <tr>
        <th>Event Title</th>
        <th>Event Location</th>
        <th>Event Time</th>
        <th>Event Date</th>
      </tr>
    </thead>
    <tbody>
        <tr>
          <td>Gathering</td>
          <td>City Centre</td>
          <td>10:30</td>
          <td>10/09/2016</td>
        </tr>
        <tr>
          <td>Meetup</td>
          <td>Some place</td>
          <td>12:30</td>
          <td>15/09/2016</td>
        </tr>
    </tbody>
  </table>