javascript:获取td索引 [英] javascript: getting td index

查看:166
本文介绍了javascript:获取td索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
Table row and column number in 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());

我在这里浏览了类似问题的结果,似乎我必须遍历所有tds或map,是否可以使用更简单的方法?谢谢.

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.

推荐答案

首先获取<td>的索引,因为它正在通往<tr>的路径:

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

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

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

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

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

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

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

这篇关于javascript:获取td索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆