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

mil*_*ilk 12 jquery html-table

例如:

<table>
<tr><td>1,1</td><td>2,1</td></tr>
<tr><td>2,1</td><td>2,2</td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我想使用以下功能:

$("td").click(function(){
alert(xxxx)
})
Run Code Online (Sandbox Code Playgroud)

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

vol*_*ron 23

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

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

   alert( [col,row].join(',') );
});
Run Code Online (Sandbox Code Playgroud)


Ale*_*hev 16

核心/指数

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

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

    alert([column, ',', row].join(''));
})
Run Code Online (Sandbox Code Playgroud)


小智 7

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

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

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

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

    alert("[" + column + ", " + row + "]");
});
Run Code Online (Sandbox Code Playgroud)