cell 에 이벤트 핸들러를 설정하고 핸들러에서 전달된 자신의 객체로 원하는 정보를 얻으면 된다.
var table = document.getElementById("myTable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
CellInfo(this);
};
}
}
function CellInfo(cell) {
alert("col: "+", "+cell.cellIndex+", row: "+cell.parentNode.rowIndex+", text: "+cell.innerText);
}
아래는 테스트를 위한 예제 소스코드이다.
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h2>테이블 클릭 핸들러 예제</h2>
<table id="myTable" style="width:100%">
<tr>
<th>회사명</th>
<th>담당자</th>
<th>연락처</th>
</tr>
<tr>
<td>(주)잘나가</td>
<td>연락해</td>
<td>010-1234-1234</td>
</tr>
<tr>
<td>막나가 주식회사</td>
<td>잘받아</td>
<td>010-0101-1212</td>
</tr>
</table>
<p>마우스로 테이블의 셀을 클릭하면 셀의 행과 열 그리고 내용을 표시합니다.</p>
<script type="text/javascript">
var table = document.getElementById("myTable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
CellInfo(this);
};
}
}
function CellInfo(cell) {
alert("col: "+", "+cell.cellIndex+", row: "+cell.parentNode.rowIndex+", text: "+cell.innerText);
}
</script>
</body>
</html>