본문 바로가기
즐거움 넘치는 IT 세계/코드로 만드는 디자인

[ jquery 기초 ] jquery Chain

by 디리씨 2019. 10. 1.
728x90

 

| Chain 이란?

jQuery의 메소드들은 반환값으로 자기 자신을 반환해야 한다는 규칙을 가지고 있다. 이를 이용하면 한번 선택한 대상에 대해서 연속적인 제어를 할 수 있다.

<html>
	<body>
		<a id="tutorial" href="http://jquery.com" target="_self">jQuery</a>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
		<script type="text/javascript">
			jQuery('#tutorial').attr('href', 'http://jquery.org').attr('target', '_blank').css('color', 'red');
		</script>
	</body>
</html>

 

예제 코드를 보면 <a>태그가 하나 있고 a태그에 href 속성과 target 속성을 jQuery 이용해 변경하려고 합니다. 해당 소스를 실행해 보면 실행된 코드는 jQuery 이용해 변경된 내용으로 출력된 것을 있습니다. , 여기서 보듯 .attr셀렉터를 이용해 연결연결하여 연속적으로 제어를 하고 있습니다. 구조가 Chain 이라고 있습니다.

1. Chain 장점

    1. 코드가 간결해진다.
    2. 인간의 언어와 유사해서 사고의 자연스러운 과정과 일치한다.

2. 탐색(traversing)

    1. Chain 대상을 바꿔서 체인을 연장 시킬수 있다.
    2. 주의사항은 너무 복잡한 chain구조는 가독성을 떨어 뜨릴 있다.

 

<html>
<body>
	<ul class="first">
		<li class="foo"> list item 1 </li>
		<li> list item 2 </li>
		<li class="bar"> list item 3 </li>
	</ul>
	<ul class="second">
		<li class="foo"> list item 1 </li>
		<li> list item 2 </li>
		<li class="bar"> list item 3 </li>
	</ul>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script type="text/javascript">$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green');</script>
</body>
</html>

 

예제 코드를 보면 ul li 이용해 간략한 표를 만들었고 jQuery 이용해 처음 ul 'first'라는 클레스를 가진것을 찾고 안에 .find() 이용해 'foo' 클레스를 가진것을 찾아 배경색상을 'red' 바꿔주고 있습니다. 그리고 .end()라는 내용이 있는데 이는 마지막에 선택되어 있는 'foo' 클레스의 선택을 한단계 앞으로 보낸주는 역할을 합니다. 그래서 한단계 앞에서 선택되어 있던 'first'라는 클레스를 가진 ul 돌아갑니다. 다시 .find 이용해 'bar'라는 클레스를 찾고 배경색상을 'green'으로 변경하고 있습니다.

 

 

728x90
반응형