[jQuery] Chain

Chain


1. Chain이란?

jQuery의 메소드들은 반환값으로 자기 자신을 반환해야 한다는 규칙을 가지고 있다.

이를 이용하면 한번 선택한 대상에 대해서 연속적인 제어를 할 수 있다.


예제1. jQuery를 이용해서 코딩하는 경우

<html>

    <body>

        <a id="tutorial" href="http://jquery.com" target="_selfxxxxx">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>


예제2. javascript의 DOM을 이용해서 코딩하는 경우

<html>

     <body>

         <a id="tutorial" href="http://jquery.com" target="_self">jQuery</a>

         <script type="text/javascript">

             var tutorial = document.getElementById('tutorial');

             tutorial.setAttribute('href', 'http://jquery.org');

             tutorial.setAttribute('target', '_blank');

             tutorial.style.color = 'red';

         </script>

     </body>

 </html>


cp.) 보충 예제

<html>

<head><title>chain이란--JQuery</title></head>

    <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://www.naver.com').attr('target', '_blank').css('color', 'green');    

        </script>

    </body>

</html>


<a>태그의 속성을 변경함 

chain의 원리

jQuery('#tutorial')

--> 리턴값.attr('href', 'http://www.naver.com')

--> 리턴값.attr('target', '_blank')

--> 리턴값.css('color', 'green')

-->사슬처럼 연속적으로 명령문을 칠 수 있다.


<html>

     <head><title>chain이란--JavaScript</title></head>

     <body>

         <a id="tutorial" href="http://jquery.com" target="_self">jQuery</a>

         <script type="text/javascript">

             var tutorial = document.getElementById('tutorial'); // jQuery('#tutorial')

             /* console.log(tutorial.setAttribute('href', 'http://jquery.org'));  */// attr('href', 'http://www.naver.com')

             tutorial.setAttribute('href', 'http://jquery.org');

             tutorial.setAttribute('target', '_blank');// attr('target', '_blank')

             tutorial.style.color = 'red'; //css('color', 'green')

         </script>

     </body>

</html> 



2. chain의 장점

- 코드가 간결해진다.

- 인간의 언어와 유사해서 사고의 자연스러운 과정과 일치함.


'WebFont-end > jQuery' 카테고리의 다른 글

[jQuery] Ajax 설정  (0) 2015.01.11
[jQuery] Ajax 기초  (0) 2014.12.07
[jQuery] Animation  (0) 2014.12.07
[jQuery] Effects  (0) 2014.12.07
[jQuery] Event  (0) 2014.12.07