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?
As per this answer, DOM Level 2 exposes cellIndex
and rowIndex
properties of td
and tr
elements, respectively.
Lets you do this, which is pretty readable:
$("td").click(function(){
var column = this.cellIndex;
var row = $(this).parentNode.rowIndex;
alert("[" + column + ", " + row + "]");
});
The index
function called with no parameters will get the position relative to its siblings (no need to traverse the hierarchy).
$('td').click(function(){
var $this = $(this);
var col = $this.index();
var row = $this.closest('tr').index();
alert( [col,row].join(',') );
});
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(''));
})
In jQuery 1.6 :
$(this).prop('cellIndex')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With