如何使用 JQuery 在表中获取 <td> 的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1415355/
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 11:24:30  来源:igfitidea点击:

How to get a <td> 's position in a table using JQuery?

jqueryhtml-table

提问by milk

For example:

例如:

<table>
<tr><td>1,1</td><td>2,1</td></tr>
<tr><td>2,1</td><td>2,2</td></tr>
</table>

I want to using the following function:

我想使用以下功能:

$("td").click(function(){
alert(xxxx)
})

to get the <td>`s position when clicked, but how?

<td>单击时获取`s位置,但是如何?

回答by vol7ron

The indexfunction called with no parameters will get the position relative to its siblings (no need to traverse the hierarchy).

index不带参数调用的函数将获得相对于其兄弟的位置(无需遍历层次结构)。

$('td').click(function(){   
   var $this = $(this);
   var col   = $this.index();
   var row   = $this.closest('tr').index();

   alert( [col,row].join(',') );
});

回答by Alex Gyoshev

Core / index

核心/指标

$("td").click(function(){

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

    alert([column, ',', row].join(''));
})

回答by adrian

As per this answer, DOM Level 2 exposes cellIndexand rowIndexproperties of tdand trelements, respectively.

按照此答案,DOM级别2自曝cellIndexrowIndex的性质tdtr分别元件。

Lets you do this, which is pretty readable:

让你这样做,这是非常可读的:

$("td").click(function(){

    var column = this.cellIndex;
    var row = $(this).parentNode.rowIndex;

    alert("[" + column + ", " + row + "]");
});

回答by user643862

In jQuery 1.6 :

在 jQuery 1.6 中:

$(this).prop('cellIndex')

回答by antelove

$("td").click(function(e){
  alert(e.target.parentElement.rowIndex + " " + e.target.cellIndex)
});
tr, td {
  padding: 0.3rem;
  border: 1px solid black
}

table:hover {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>0, 0</td>
    <td>0, 1</td>
    <td>0, 2</td>
  </tr>
  <tr>
    <td>1, 0</td>
    <td>1, 1</td>
    <td>1, 2</td>
  </tr>
</table>