jQuery javascript:获取 td 索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6470877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:55:28  来源:igfitidea点击:

javascript: getting td index

jqueryxhtml

提问by PruitIgoe

Possible Duplicate:
Table row and column number in jQuery

可能的重复:
jQuery 中的表行和列号

If I have a table like so:

如果我有一张像这样的桌子:

<table>
  <thead>
     <tr><th>1</th> <th>2</th> <th>3</th></tr>
  </thead>

  <tbody>
    <tr><td>data</td> <td>checkbox</td> <td>data</td></tr>
  </tbody>
</table>

When the user clicks the checkbox, I want to get the row and column indices. I can get the row index by using this code:

当用户单击复选框时,我想获取行和列索引。我可以使用以下代码获取行索引:

 var row = $(this).parent().parent();
 var rowIndex = $(row[0].rowIndex);

but I can't figure out the column index...

但我无法弄清楚列索引...

I tried this but it didn't work:

我试过这个,但没有用:

 var colIndex = $(row.children().index(this).parent());

I looked through the results of similar questions here and it seems I have to iterate through all the tds with each or map, is there something simpler that I can use? Thanks.

我在这里查看了类似问题的结果,似乎我必须使用每个或地图遍历所有 tds,有没有更简单的东西可以使用?谢谢。

回答by user113716

Get the index of the <td>first, since it is on the way to the <tr>:

获取第一个的索引<td>,因为它正在前往<tr>

var cell = $(this).closest('td');
var cellIndex = cell[0].cellIndex

var row = cell.closest('tr');
var rowIndex = row[0].rowIndex;

Or using the parents()[docs]method along with a multiple-selector[docs], you could do the selection for both at once:

或者使用parents()[docs]方法和multiple-selector[docs],您可以同时为两者进行选择:

var cellAndRow = $(this).parents('td,tr');

var cellIndex = cellAndRow[0].cellIndex
var rowIndex = cellAndRow[1].rowIndex;