테이블 안 체크박스를 클릭하면 해당 Row의 배경 색이 변경되는 코딩 방법을 알아 보도록 하겠습니다.
자바스크립트를 사용하여 간단하게 체크 된 라인의 배경색을 변경 할 수 있습니다.
먼저 전체 소스를 살펴 보도록 하겠습니다.
전체소스
<head>
<title>체크박스 클릭 시 해당 테이블 줄 배경색 변경하기</title>
<script>
function setBg(t) {
td = t.parentNode;
td.style.backgroundColor = (t.checked) ? "blue" : "white";
tr = t.parentNode.parentNode;
tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";
}
</script>
</head>
<body>
<table width="100%;" border=1 cellspacing=0 cellpadding=5>
<tr>
<td width=20><input type="checkbox" onclick="setBg(this)"></td>
<td>이런조이</td>
</tr>
<tr>
<td><input type="checkbox" onclick="setBg(this)"></td>
<td>체크박스 체크하면</td>
</tr>
<tr>
<td><input type="checkbox" onclick="setBg(this)"></td>
<td>테이블의 체크 된 라인의 색이 변경 됩니다</td>
</tr>
</table>
</body>
</html>
설명
<input type="checkbox" onclick="setBg(this)">
→ onclick="setBg(this)"
체크박스를 클릭 했을 경우 setBg 함수를 호출하게 됩니다. this란 현재 자신의 정보를 객체로 보내게 됩니다.
2. 호출 자바스크립트
function setBg(t) {
td = t.parentNode;
td.style.backgroundColor = (t.checked) ? "blue" : "white";
tr = t.parentNode.parentNode;
tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";
}
→ setBg(t)
넘겨준 this는 t라는 변수명으로 받게 됩니다.
→ t.parentNode
넘어 온 객체(t)의 부모노드(parentNode)를 가리키게 됩니다. 따라서 체크박스 상위의 노드는 <td> 가 됩니다.
→ td.style.backgroundColor = (t.checked) ? "blue" : "white";
<td>의 배경색을 변경 합니다. 만약 체크되어 있다면 blue 체크 안되어 있다면 white 로 변경 합니다.
※ 판단대상 ? 참이면적용 : 거짓이면적용
→ tr = t.parentNode.parentNode;
체크박스객체.부모노드.부모노드 의 객체는 <tr> 이 됩니다.
→ tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";
<tr>의 배경색을 변경 하게 됩니다.
결과
실습
이런조이 | |
체크박스 체크하면 | |
테이블의 체크 된 라인의 색이 변경 됩니다 |
HTML 과 자바스크립트를 이용한 테이블 안 체크박스를 클릭 했을 경우 해당 줄의 색을 변경하는 코딩을 알아 보았습니다.
'프로그래밍 > HTML, CSS, JavaScript' 카테고리의 다른 글
자바스크립트 replace 문자 모두 바꾸기 - 예제/실습 (5) | 2018.09.28 |
---|---|
HTML/CSS 이미지효과 - 마우스 오버시에 텍스트 보이기 예제소스 (6) | 2018.08.01 |
[HTML/CSS] DIV 중앙, 가운데 배치하기 (6) | 2018.07.01 |
[JavaScript] 펼쳐지는 세로 트리메뉴 쉽게 만들기 (3) | 2018.06.25 |
[자바스크립트] 일정간격으로 배경 색 변경하기- setInterval (2) | 2018.06.20 |