Reputation: 139
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?
Upvotes: 12
Views: 31804
Reputation: 3358
$("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>
Upvotes: 1
Reputation: 1751
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 + "]");
});
Upvotes: 8
Reputation: 42149
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(',') );
});
Upvotes: 24
Reputation: 11977
$("td").click(function(){
var column = $(this).parent().children().index(this);
var row = $(this).parent().parent().children().index(this.parentNode);
alert([column, ',', row].join(''));
})
Upvotes: 16