Así que tengo esta tabla, y cuando hago clic en td
me gustaría saber dónde está eso (qué fila y celda) sin ningún atributo en los elementos.Obtener ubicación de celda
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td> // If I click on this I would like to know tr:1 & td:2
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
Javascript:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
// Track my location;
// example: I'm in table row 1 and I'm the 2th cell of this row
}
}
jQuery tiene el método útil [ '$ .index()'] (http://api.jquery.com/index/) que puede hacer esto por usted si está abierto a marcos. – Sampson
No quiero usar ningún framework, pero intentaré ver qué hace esa función en jQuery. – Adam
Puede ver un ejemplo usando '$ .index()' en línea en [http://jsbin.com/okuri4](http://jsbin.com/okuri4) pero [@patrickdw] (http: // stackoverflow. com/questions/4998953/javascript-get-cell-location/4999018 # 4999018) la respuesta a continuación parece ser la mejor para usted. – Sampson