2009-09-12 9 views

risposta

16

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('')); 
}) 
+0

ho provato e ha funzionato, vi ringrazio molto :) – milk

2

In jQuery 1.6:

$(this).prop('cellIndex') 
21

La funzione index chiamato senza parametri otterrà la posizione relativa ai suoi fratelli (senza necessità di attraversare la gerarchia).

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

    alert([col,row].join(',')); 
}); 
7

Secondo this answer, DOM Livello 2 espone cellIndex e rowIndex proprietà di td e tr elementi, rispettivamente.

ti permette di fare questo, che è abbastanza leggibile:.

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

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

    alert("[" + column + ", " + row + "]"); 
}); 
+0

questo codice non potrà mai funzionare così com'è dato che stai chiamando 'cellIndex' su un oggetto jQuery, usa' this.cellIndex' invece di '$ (this) .cellIndex', lo stesso per ottenere la riga –

0

$("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>

Problemi correlati