본문 바로가기
프로그래밍 개발/JQuery

JQuery Chain

by Jinseok Kim 2020. 12. 23.
반응형

 

 

Chain

 

 

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

 

 

chain의 장점

 

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

 

 

예시

<html>
    <body>
        <a id="tutorial" href="http://jquery.com" target="_self">Jin seok kim</a>
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script>
            $('#tutorial').attr('href', 'http://jquery.org').attr('target', '_blank').css('color', 'red');
            //.attr 메소드를 통해 href 값을 바꿔주었고 연속으로 .attr을 적용시켜 문자의 언더바, 문자 색 까지
            //바꿨다.
        </script>
    </body>
</html>

 

 

 

 

탐색(traversing)

 

 

  • chain의 대상을 바꿔서 체인을 계속 연장시킬 수 있는 방법
  • 너무 복잡한 chain은 코드의 가독성을 떨어 뜨릴 수 있다.

 

참고 사이트

http://api.jquery.com/category/traversing/

 

Traversing | jQuery API Documentation

Create a new jQuery object with elements added to the set of matched elements. Add the previous set of elements on the stack to the current set, optionally filtered by a selector. Add the previous set of elements on the stack to the current set. Get the ch

api.jquery.com

 

 

<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 src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        
  <script >$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green');
       //.find 메소드로 class 값이 foo인 엘리먼트를 찾으면 뒤에 따라오는 메소드 효과들을 적용할 수 있다.
       //.end 메소드는 다시 처음 엘리멘트 값을 지정했던$('ul.first')으로 돌아가 시작하게 하는 기능을 담당한다.
  </script>
    </body>
</html>

 

 

 

 

 

 

반응형

'프로그래밍 개발 > JQuery' 카테고리의 다른 글

JQuery 엘리먼트 제어  (0) 2020.12.28
JQuery Event  (0) 2020.12.25
JQuery 선택자  (0) 2020.12.22
JQuery Wrapper  (0) 2020.12.18
JQuery 이란  (0) 2020.12.18

댓글