2015-03-13 17 views
9

Tôi muốn biết cách nhấp vào nút trong bảng HTML và nhận số hàng và cột được trả lại cho tôi: Ví dụ: bảng:Nhấp vào bảng HTML và nhận số hàng (với javascript, không phải 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> 

Làm cách nào để sử dụng JavaScript để nhấp vào nút đầu tiên ở hàng thứ hai và cho tôi biết rằng tôi đã nhấp vào ô đầu tiên ở hàng thứ hai? Mỗi nút có cần phải có một id duy nhất hay không?

+0

Hàng có [ 'rowIndex'] (https: //developer.mozilla. org/en-US/docs/Web/API/HTMLTableRowElement/rowIndex). và các ô có ['cellIndex'] (https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement). Bạn có thể sử dụng chúng [như vậy ...] (http://jsfiddle.net/eoemydb5/) – Teemu

Trả lời

20

Hãy thử điều này:

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

Bạn có thể dễ dàng thêm điều này vào TD và thả một trong các hàm parentNode thành không sử dụng các nút. – Gremash

+2

Tôi thử "element.parentNode.parentNode.rowIndex" nhưng nó trả về không xác định – anhtv13

3

phiên bản generic Hầu hết các chức năng @Gremash js

function getId(element) { 
    alert("row" + element.closest('tr').rowIndex + 
    " -column" + element.closest('td').cellIndex); 
} 
Các vấn đề liên quan