위와 같은 테이블이 있고, 계산결과 버튼을 클릭하면 alert 창으로
결과값을 알려주는 프로그램을 작성해보려고 한다.
특정 <tr>의 특정 <td> 값에 접근하면 간단하게 만들 수 있는 프로그램이다.
1. 간단한 CSS가 포함된 테이블 만들기
<head>
<meta charset="UTF-8">
<style type="text/css">
table {
width: 500px;
height: 200px;
text-align: center;
border-spacing: 0;
}
tr td:first-child {
font-weight: bolder;
}
</style>
</head>
<body>
<table id='tbl' border="1">
<tr>
<th>첨자</th>
<th>a</th>
<th>b</th>
<th>a x b</th>
</tr>
<tr>
<td>0</td>
<td>5</td>
<td>33</td>
<td><input type="button" value="계산결과" onclick="result(1)"></td>
</tr>
<tr>
<td>1</td>
<td>12</td>
<td>14</td>
<td><input type="button" value="계산결과" onclick="result(2)"></td>
</tr>
<tr>
<td>2</td>
<td>18</td>
<td>32</td>
<td><input type="button" value="계산결과" onclick="result(3)"></td>
</tr>
</table>
</body>
<table> 태그의 id 프로퍼티에 id 값을 주고, thead 행을 제외한 각 행에 있는 계산결과 버튼을 누르면
onclick 이벤트 처리기가 발생 하도록 했다. 함수의 파라메터로는 행 번호를 주면 되겠다.
2. JS코드로 특정 <tr>의 특정 <td>값 얻어내기
<script type="text/javascript">
function result(rnum) {
let table = document.getElementById('tbl');
let rowList = table.rows;
console.log(rowList);
let row = rowList[parseInt(rnum)];
alert(row.cells[1].innerHTML * row.cells[2].innerHTML);
}
</script>
table 변수에 <table>를 담고, table의 rows를 rowList에 담으면 HTMLCollection 타입으로 담기게 된다.
이 중에서 접근하고자 하는 행을 row 변수에 담은 후 a의 값이 있는 cells[1], b의 값이 있는 cells[2]를
곱한 값을 alert의 파라메터로 넣어주면 원하는 결과를 출력할 수 있다.
3. 결과
'FRONT-END > JAVASCRIPT' 카테고리의 다른 글
[JS] JSON의 정의와 함수 사용 방법 (0) | 2023.02.02 |
---|---|
[JS] XMLHttpRequest (0) | 2023.02.01 |
[JS] JS를 이용하여 TABLE 만들기 (0) | 2023.01.31 |
[JS] onkeydown, onkeypress 차이점 (0) | 2023.01.31 |
[JS] input type="checkbox" 일 때 이벤트 핸들러 활용 (0) | 2023.01.30 |
댓글