본문 바로가기

Java Script/work

테이블속 값을 가져와 연산처리 하기, nodeList

방법1

<body>
<table border="1">
<col width="100"><col width="100"><col width="100"><col width="100">
	<tr bgcolor="gray">
		<th style="color: white">첨자</th><th>a</th><th>b</th><th>axb을 계산</th>
	</tr>
	<tr>
		<th bgcolor="gray" style="color: white">0</th><td>5</td><td>33</td><td><button type="button" 
			onclick="result(5,33)">계산 결과</button> </td>
	</tr>
	<tr>
		<th bgcolor="gray" style="color: white">1</th><td>12</td><td>14</td><td><button type="button" 
			onclick="result(12,14)">계산 결과</button> </td>
	</tr>
	<tr>
		<th bgcolor="gray" style="color: white">2</th><td>18</td><td>65</td><td><button type="button" 
			onclick="result(18,65)">계산 결과</button> </td>
	</tr>
</table>
<script type="text/javascript">
function result(num1, num2) {
	alert(num1*num2);
}
</script>
</body>

 

 

 

 

 

 

 

 

방법2 : nodeList 사용

 

node를 통해 td Tag를 받고 list로 값을 대입하여 출력함

1//

<script type="text/javascript">
let a = new Array(3);
let b = new Array(3);

for(i = 0;i < 3; i++){
	a[i] = document.getElementById("n" + (i + 1) + "1").innerHTML
	b[i] = document.getElementById("n" + (i + 1) + "2").innerHTML
}

function multi( index ) {
	let result = a[index] * b[index];
	alert("결과는 " + result + " 입니다");
}
</script>

 

 

2//

<script type="text/javascript">
let nodeNum = document.getElementsByTagName('td');
// alert(nodeNum[3].innerHTML);	// 0 1 3 4 6 7

let a = new Array(3);
let b = new Array(3);

for(i = 0;i < 3; i++){
	a[i] = nodeNum[0 + (3 * i)].innerHTML;
	b[i] = nodeNum[1 + (3 * i)].innerHTML;
}

function multi( index ) {
	let result = a[index] * b[index];
	alert("결과는 " + result + " 입니다");
}
</script>