2011-02-15 33 views
5

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 
    } 
} 
+0

jQuery tiene el método útil [ '$ .index()'] (http://api.jquery.com/index/) que puede hacer esto por usted si está abierto a marcos. – Sampson

+0

No quiero usar ningún framework, pero intentaré ver qué hace esa función en jQuery. – Adam

+0

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

Respuesta

17

En el controlador, this es la celda de la tabla, por lo que para el índice de células ello:

var cellIndex = this.cellIndex + 1; // the + 1 is to give a 1 based index 

y para el índice de la fila, hacer esto:

var rowIndex = this.parentNode.rowIndex + 1; 

Ejemplo:http://jsfiddle.net/fwZTc/1/

1

Bueno, cuando usted tiene rowspan/ColSpan puede tener mucho más divertido, sin embargo, si la red es regular, sólo puede determinar su posición en el índice de haciendo:

row = Math.floor(i/rows); 
column = i % columns; 
+0

no es normal :) Me gustaría usar rowspan y colspan también, pero gracias por el consejo :)) – Adam

1

Este bloque de script le proporcionará la información que desea, mediante la adición de la información como propiedades de la célula y luego acceder a ellos en la función onclick:

// Track onclicks on all td elements 
var table = document.getElementsByTagName("table")[0]; 
// Get all the rows in the table 
var rows = table.getElementsByTagName("tr"); 

for (var i = 0; i < rows.length; i++) { 
    //Get the cells in the given row 
    var cells = rows[i].getElementsByTagName("td"); 
    for (var j = 0; j < cells.length; j++) { 
     // Cell Object 
     var cell = cells[j]; 
     cell.rowIndex = i; 
     cell.positionIndex = j; 
     cell.totalCells = cells.length; 
     cell.totalRows = rows.length; 
     // Track with onclick 
     console.log(cell); 
     cell.onclick = function() { 
      alert("I am in row " + this.rowIndex + " (out of " + this.totalRows + " rows) and I am position " + this.positionIndex + " (out of " + this.totalCells + " cells)"); 
     }; 
    } 
} 
0

El uso de "este" en la mesa de células

function myFunction(x) { 
 
     var tr = x.parentNode.rowIndex; 
 
     var td = x.cellIndex;   
 
     
 
     document.getElementById("tr").innerHTML = "Row index is: " + tr; 
 
     document.getElementById("td").innerHTML = "Column index is: " + td; 
 
     }
tr, th, td { 
 
    padding: 0.6rem; 
 
    border: 1px solid black 
 
} 
 

 
table:hover { 
 
    cursor: pointer; 
 
}
<table> 
 
    <tbody> 
 
     <tr> 
 
      <td onclick="myFunction(this)">1</td> 
 
      <td onclick="myFunction(this)">2</td> 
 
      <td onclick="myFunction(this)">3</td> 
 
     </tr> 
 

 
     <tr> 
 
      <td onclick="myFunction(this)">4</td> 
 
      <td onclick="myFunction(this)">5</td> 
 
      <td onclick="myFunction(this)">6</td> 
 
     </tr> 
 

 
     <tr> 
 
      <td onclick="myFunction(this)">7</td> 
 
      <td onclick="myFunction(this)">8</td> 
 
      <td onclick="myFunction(this)">9</td> 
 
     </tr> 
 
    </tbody> 
 
</table> 
 

 
<p id="tr"></p> 
 
<p id="td"></p>

Cuestiones relacionadas