2015-03-13 9 views
9

Chciałbym wiedzieć, jak kliknąć przycisk w tabeli HTML i uzyskać numer wiersza i kolumny zwróconej do mnie: Na przykład z następującymi tabela:Kliknij tabelę HTML i uzyskaj numer wiersza (z javascript, a nie 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> 

Jak użyłbym JavaScript, aby kliknąć na pierwszy przycisk w drugim rzędzie i mają to powiedzieć, że kliknąłem na pierwszej komórki w drugim rzędzie? Czy każdy przycisk musi mieć unikalny identyfikator, czy nie?

+0

wierszy [ 'rowIndex'] (https: //developer.mozilla. org/en-US/docs/Web/API/HTMLTableRowElement/rowIndex). a komórki mają ['cellIndex'] (https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement). Możesz ich użyć [jak ...] (http://jsfiddle.net/eoemydb5/) – Teemu

Odpowiedz

20

Spróbuj tego:

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

Możesz łatwo dodać to do TD i upuścić jedną z funkcji parentNode, aby nie użyj przycisków. – Gremash

+2

Próbuję "element.parentNode.parentNode.rowIndex", ale zwraca undefined – anhtv13

3

większość typowych wersję funkcji @Gremash js

function getId(element) { 
    alert("row" + element.closest('tr').rowIndex + 
    " -column" + element.closest('td').cellIndex); 
} 
Powiązane problemy