본문 바로가기
study/Jquery

[Jquery] 21. Jquery table ($(this).index(), $(this).parent().children().index(this), td:nth-of-type())

by 금이패런츠 2022. 4. 25.
728x90
반응형
<!DOCTYPE html>
<!-- src/main/webapp/20220425/table1.html -->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	table, th, td { border : 3px solid #222222;		border-collapse: collapse;	}
	.header { background:green; color:yellow;	}
	.reverse { background:blue; color:white;	}
	.hover { background:skyblue; color:blue;	}
</style>
<script type="text/javascript"
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script type="text/javascript">
	$(function(){
		$("tr").hover(function(){
			//$(this).index() : tr 태그의 인덱스 리턴
//			if($(this).index() != 0) {
	
			if(!$(this).is(".header")) { //$(this)태그의 class속성이 header가 아닌경우
				$(this).addClass("reverse")
			}
		},function(){
			$(this).removeClass("reverse")
		})
		$("th").hover(function(){
			//$(this) 					  : 마우스커서를 가지고 있는 th태그
			//$(this).parent() 			  : th태그의 상위태그. tr태그
			//$(this).parent().children() : tr태그의 하위 태그들. th태그들
			//len : th 태그의 갯수
			var len = $(this).parent().children().length
			//$(this).parent().children().index(this) : th태그의 인덱스값
			//select : 이벤트를 가지고 있는 th태그의 순번
			select = $(this).parent().children().index(this) + 1;
			//td:nth-of-type() : td태그의 순번
			//$("td:nth-of-type(4n+1)")
			$("td:nth-of-type(" + len + "n + " + select + ")").addClass("hover");
		},function(){
			var len = $(this).parent().children().length
			select = $(this).parent().children().index(this) + 1;
			$("td:nth-of-type(" + len + "n + " + select + ")").removeClass("hover");
		})
	})
</script>
</head>
<body>
<table>
	<tr class="header">
		<th>이름</th>
		<th>혈액형</th>
		<th>지역</th>
		<th>성별</th>
	</tr>
	<tr>
		<td>강민</td>
		<td>AB형</td>
		<td>서울</td>
		<td>남자</td>
	</tr>
	<tr>
		<td>구자연</td>
		<td>B형</td>
		<td>일산</td>
		<td>여자</td>
	</tr>
	<tr>
		<td>김미화</td>
		<td>A형</td>
		<td>대구</td>
		<td>여자</td>
	</tr>
	<tr>
		<td>이선희</td>
		<td>O형</td>
		<td>광주</td>
		<td>여자</td>
	</tr>
	<tr>
		<td>남기주</td>
		<td>B형</td>
		<td>부산</td>
		<td>남자</td>
	</tr>
	<tr>
		<td>윤미란</td>
		<td>A형</td>
		<td>대전</td>
		<td>여자</td>
	</tr>
</table>
</body>
</html>
728x90
반응형