프로그래밍/JQuery

실무에서 자주 쓰이는 JQuery 제이쿼리 모음

Jay Tech 2017. 3. 5. 14:05
반응형

제이쿼리는 타겟을 잡는 것이 중요하다. 꼭 알아야 하는 중요한 것들만 보자.


테스트하기 좋게 여러 버튼이 있는 페이지를 써볼 것이다. 






소스의 일부를 발췌하였다.


<div class="row">

   <div class="content buttons-with-margin">

        <div class="container-fluid">

            <div class="row">

                <div class="col-md-12">

                    <div class="card">

                        <div class="row">

                            <div class="col-md-6">

                                <div class="header">

                                    <h4 class="title">Colors</h4>

                                </div>

                                <div class="content">

                                    <button class="btn btn-default btn-fill btn-wd" id="defaultBtId0">Default</button>

                                    <button class="btn btn-primary btn-fill btn-wd" id="defaultBtId1">Primary</button>

                                    <button class="btn btn-info btn-fill btn-wd" id="defaultBtId2">Info</button>

                                    <button class="btn btn-success btn-fill btn-wd" id="defaultBtId3">Success</button>

                                    <button class="btn btn-warning btn-fill btn-wd">Warning</button>

                                    <button class="btn btn-danger btn-fill btn-wd">Danger</button>

                                </div>

                            </div>

                            <div class="col-md-6">

                                <div class="header">

                                    <h4 class="title">Styles</h4>

                                </div>

                                <div class="content">

                                    <button class="btn btn-wd">Default</button>

                                    <button class="btn btn-fill btn-wd">Fill</button>

                                    <button class="btn btn-fill btn-round btn-wd">Fill + Round</button>

                                    <button class="btn btn-round btn-wd">Round</button>

                                    <button class="btn btn-simple btn-wd">Simple</button>

                                </div>

//....................



1. 먼저 타겟 잡는 법이다



$("#defaultBtId0").css("border", "8px solid #ff0000");


쩜(.)을 기준으로 왼쪽이 target이다. 지금은 아이디가(#) defaultBtId0 인 놈을 잡았다. 쩜의 오른쪽은 무엇을 시킬지 즉, 행위이다.


JQuery API에서 발췌하였다.


.css()


Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.


형광색 칠해져 있는 부분이다. 즉, css의 속성을 바꾸는 함수이다. 순서대로 파라미터에 (이름, 속성) 이 들어간다.

문제에서는 border (경계선) 의 두께를 8px 색을 빨간색으로 바꾸었다.


결과화면) 이렇게 타겟잡은 버튼에 테두리가 생겼다.






2-1. 자식 잡는 법


어감이 이상하지만 특정 태그 밑의 자식을 잡아서 효과를 주는 것도 많이 쓰인다.


$("div div.col-md-12").css("border", "8px solid #ff0000");

$("div>div.col-md-12").css("border", "8px solid #ff0000");


둘 다 같은 의미이다. 즉 div태그 아래의 div.col-md-12 인 놈을 모두 잡아라. 잡아서 테두리를 쳐라



결과화면) 전체에 테두리가 쳐졌다.






2-2. 저 Colors밑에 있는 버튼을 전부 글자를 바꾸고 싶다.


<div id="contentId" class="content">

   <button class="btn btn-default btn-fill btn-wd" id="defaultBtId0">Default</button>

   <button class="btn btn-primary btn-fill btn-wd" id="defaultBtId1">Primary</button>

   <button class="btn btn-info btn-fill btn-wd" id="defaultBtId2">Info</button>

   <button class="btn btn-success btn-fill btn-wd" id="defaultBtId3">Success</button>

   <button class="btn btn-warning btn-fill btn-wd">Warning</button>

   <button class="btn btn-danger btn-fill btn-wd">Danger</button>


컨텐트에 아이디를 하나 주자.


주고 나서 


 $("#contentId button").html("허허헣");



결과화면)





3. 특정 클래스를 가진 놈들에게 모두 효과 적용하기


예를들어 class = "btn-fill" 이라는 가진 놈들을 컨트롤하고 싶은데 문제가 있다.

<button class="btn btn-success btn-fill btn-wd">

<button class="btn btn-fill btn-round btn-wd">

<button class="btn btn-default btn-fill" > 등등......


..... 앞에도 있고 가운데에도 있고 끝에 있는 놈들도 있다. 이럴 땐 어떻게 할까?



 $("[class*=btn-fill]").css("border","8px solid #ff0000");


*= 의 의미는 클래스가 btn-fill인 것이 왼쪽 가운데 오른쪽 하나있던 같이 있던 전부 다 찾아라 라는 의미이다.



결과화면) 전부 다 찾았다.






4. 여러개 중에서 특정 번째의 것을 가져오고 싶다.


Colors안에 버튼이 6개가 있는데 이중 3번째 것을 가져오고 싶다. 아까 contentId를 줬던 것을 활용할 것이다.


var $jList = $("#contentId>button");

var jList2 = $jList.eq(2);

jList2.css("border","8px solid #ff0000");


첫 라인에서 변수앞에 $를 붙였다. 변수앞에 $를 붙이면 뭔가 바뀌는 것이 아니다. 참고로 변수명 지을때 허용하는 문자이다. 하지만 가독성때문에 암묵적으로 약속한다. 왜냐하면 $("#contentId>button"); 은 안에 제이쿼리 타겟이 들어있기 때문이다. 즉, 타겟을 잡았다는 것을 알기 쉽게하려고 $를 붙인 것이다. 


두 번째 라인을 보자. 타겟들 중에서 3번 째 것을 가져온다 (0부터 시작이므로)


jquery api 일부를 발췌하였다.


.eq()

.eq( index )Returns: jQuery

Description: Reduce the set of matched elements to the one at the specified index.

  • version added: 1.1.2.eq( index )

    • index
      Type: Integer
      An integer indicating the 0-based position of the element.
  • version added: 1.4.eq( indexFromEnd )

    • indexFromEnd
      Type: Integer
      An integer indicating the position of the element, counting backwards from the last element in the set.

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.

Consider a page with a simple list on it:

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

We can apply this method to the set of list items:

1
$( "li" ).eq( 2 ).css( "background-color", "red" );


마지막 세 번째 라인은 잡은 타겟에 css속성을 적용한다.


그런데 왜 굳이 변수를 하나 더 만들어서 타겟잡은 것에서 꺼냈을까? 이유는 $로 타겟을 잡을 때는 매 회 객체가 계속 생성된다. 하지만 var $jList에 넣어 놓음으로써 한번만 생성할 수 있게 한다. 메모리 낭비를 줄이기 위해서이다. (싱글톤형식으로 유지한다)

반응형