如何使用jquery在TD上获取行索引

时间:2017-07-03 14:43:13

标签: javascript jquery jquery-plugins

我正在尝试获取用户单击的单元格的行号和列号 我的代码给出了正确的列,但行没有给出0和1

我正在使用以下代码    帮我找到为什么不给总行0和1

的原因
<script>
 $('td').click(function(){
 col = $(this).parent().children().index($(this));
 row = $(this).parent().parent().children().index($(this).parent());
 alert("row no:"+row+"col no :"+col);
 </script>

2 个答案:

答案 0 :(得分:3)

您只需使用$(element).index()即可在其兄弟姐妹中获取该元素的索引

&#13;
&#13;
$('td').click(function() {
  var col = $(this).index(),
    row = $(this).parent().index();

  console.log("row index:" + row + ", col index :" + col);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 4</td>
    <td>Item 5</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 4</td>
    <td>Item 5</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 4</td>
    <td>Item 5</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 4</td>
    <td>Item 5</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 4</td>
    <td>Item 5</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果使用.cellIndex.rowIndex,没有jQuery会更简单,更快捷。

$('td').click(function(){
  var col = this.cellIndex,
      row = this.parentNode.rowIndex;
  alert("row no:"+row+"col no :"+col);

正如下面@PatrickRoberts所指出的那样,旧的Opera的行为(版本12及更低版本)的不同之处在于它尊重您提供的HTML中的thead/tbody/tfoot顺序,因此如果您放置{{1}在tfoot之上(它应该去的地方),它有一行或多行,tbody行将偏移那么多。

正确的行为是考虑顶部的tbody和底部的thead,无论它们在何处定义。

现在,Opera不再是一个问题,因为它现在使用Chrome的Webkit fork,所以行为是一致的。

另请注意,jQuery的手动tbody计算仅考虑给定.index()的子项,假设此处为上下文。

相关问题