2015-03-13 12 views
9

Vorrei sapere come fare clic su un pulsante in una tabella HTML e ottenere il numero di riga e colonna restituito a me: Ad esempio, con il seguente tabella:Fare clic su tabella HTML e ottenere il numero di riga (con javascript, non jquery)

<table> 
    <tr> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    </tr> 
    <tr> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    </tr> 
    <tr> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    <td><input type="button" value="button"></td> 
    </tr> 
    </table> 

Come vorrei utilizzare JavaScript per fare clic sul primo pulsante in seconda fila e lo hanno mi dicono che ho cliccato sulla prima cella in seconda fila? Ogni pulsante deve avere un ID univoco o no?

+0

righe sono [ 'rowIndex'] (https: //developer.mozilla. org/it-IT/docs/Web/API/HTMLTableRowElement/rowIndex). e le celle hanno ['cellIndex'] (https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement). Puoi usarli [come così ...] (http://jsfiddle.net/eoemydb5/) – Teemu

risposta

20

Prova questo:

function getId(element) { 
 
    alert("row" + element.parentNode.parentNode.rowIndex + 
 
    " - column" + element.parentNode.cellIndex); 
 
}
<table> 
 
    <tr> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    </tr> 
 
    <tr> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    </tr> 
 
    <tr> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    <td><input type="button" value="button" onclick="getId(this)"></td> 
 
    </tr> 
 
</table>

+0

Puoi facilmente aggiungere questo al TD e rilasciare una delle funzioni parentNode per non usa i pulsanti. – Gremash

+2

Provo "element.parentNode.parentNode.rowIndex" ma restituisce undefined – anhtv13

3

versione più generica di @Gremash js funzione

function getId(element) { 
    alert("row" + element.closest('tr').rowIndex + 
    " -column" + element.closest('td').cellIndex); 
} 
Problemi correlati