jQuery

 

jQuery 다루기

 

  • jQuery 여러 기능들

 

화면에 새로운 HTML을 생성하여 나타내여라! - $( )
  1. $( "<div> 안녕 하세요 </div>" );
  • 정말 요즘 인기 있는 개그프로처럼 "참~~ 쉽죠잉~~" 이다. 그냥 $(" ")넣어만 주면 HTML로 출력 된다는 것이다.

예제 : http://gisung2.cafe24.com/jquery/chapter2/new.divs.html

 

확장된 집합을 배열로 접근하자
  1. $('span[title]')[0]
  • 위 코드는 모든 span 엘리먼트의 title속성값의 0 == 첫번째 값을 반환한다. (jQuery의 반화값은 자바스크립트 배열과 매우 유사한 형태임으로 배열 & length & size();를 사용할 수 있고 값을 얻어 오기 위해 get()이란 메서드를 사용할 수도 있다.

  1. $('span[title]').get(0)

도 가능 하다는 뜻이다^^;

 

이미 선택된 셀렉터에 추가 하기 - add - Add elements to the set of matched elements.
  1. $('span[title], span[title]')
    또는
    $('span[title]').add(span[title])

 

  1. <script>
        $(document).ready(function(){   
           $("div").css("border", "2px solid red")
               .add("p")
               .css("background", "yellow");
        });
    </script>

 

http://docs.jquery.com/Traversing/add#expr [새창으로 여세요]

  • add는 기존의 확장 집합에 새로운 확장집합을 추가 한다고 생각하면 된다.^^; 또 add()  메서드는 HTML을 동적으로 엘리먼트에 추가 할수 있다.

http://api.jquery.com/add/

 

엘리먼트 순회하기 - each - Iterate over a jQuery object, executing a function for each matched element.
  1. $('li').each(function(index) {
        alert(index + ': ' + $(this).text());
      });

  • .each 셀렉터와 일치하는 집합을 돌면서 해당 엘리먼트를 호출한다. 여기서의 this는 현재의 현재 가르키는 엘리먼트이다. 위 예제는 현재 엘리먼트의 text를 alert로 보여주게 된다.

http://gisung2.cafe24.com/jquery/study/each1_1.jsp

클릭시 toggleClass란 메소드를 각각의 엘리먼트에 적용하는 예제 이다.

 

속성값 설정하기 - attr - Get the value of an attribute for the first element in the set of matched elements.
  1. <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />
  2.  
  3. $('#greatphoto').attr('alt', 'Beijing Brush Seller');
  4.  
  5. $('#greatphoto')
      .attr('title', 'Photo by Kelly Clark');

    $('#greatphoto').attr({
      alt: 'Beijing Brush Seller',
      title: 'photo by Kelly Clark'
    });
  6.  
  7. $('#greatphoto').attr('title', function() {
      return this.alt + ' - photo by Kelly Clark'
    );
  8.  
  9. $('img').attr('alt', function(index){
       return this.title;
    });
  • 개발을 하다보면 엘리먼트의 속성값이 접근해야 할 경우가 많다. jQuery의 attr을 사용하여 쉽게 속성값을 변경하고 얻어 올 수 있다. 셀렉터에 의해 반환된 집합이 한개 이상이라면 엘리먼트를 돌면서 해당되는 엘리먼트에 접근하는 것이 가능한다. 또한 한번에 다수의 엘리먼트를 설정하고 싶을때는 위 두번째, 세번재 예제와 같이 하면 된다. attr 은 명시한 속성이 없으면 undefined를 리턴한다. 

클래스 추가 제거 하기 - addClass, removeClass - Adds the specified class(es) to each of the set of matched elements., Remove one or all classes from each element in the set of matched elements.
  1. $('p').addClass('myClass yourClass');


    $('p').removeClass('myClass noClass').addClass('yourClass');


    $('ul li:last').addClass(function() {
      return 'item-' + $(this).index();
    });

  • addClass 는 반환된 집합에 인자로 받은 클래스를 적용한다.
  • removeClass 는 반환된 집합에 인자로 받은 클래스를 제거 한다.

http://gisung2.cafe24.com/jquery/study/addClass1_1.jsp 

클래스 변경하기 -  toggleClass - Add or remove a class from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
  1. $('#foo').toggleClass(className, addOrRemove);

    if (addOrRemove) {
        $('#foo').addClass(className);
      }
      else {
        $('#foo').removeClass(className);
      }
    }
     
    $('div.foo').toggleClass(function() {
      if ($(this).parent().is('.bar') {
        return 'happy';
      } else {
        return 'sad';
      }
    });

  • toggleClass 메서드의 매개변수로 전달받은 클래스가 셀렉터에 의해 선택되어진 확장 엘리먼트에 이미 적용되어 있다면 제거 하고 그렇지 않다면 추가한다. 

css 설정 하기 - css - Get the value of a style property for the first element in the set of matched elements.
  1. .css( propertyName )
    .css( propertyName, value )
    .css( propertyName, function(index, value) )

  • css()메서드를 이용하여 css를 설정하고 또는 값을 얻어 올 수 있다. 첫번째 propertyName 하나만 인자로 주어진 경우에는 설정되어 있는 값을 리턴한다. 인자가 두개인 경우엔 해당 property에 value값을 넣게 된다. 

셀렉터와 일치하는 엘리먼트가 있는지 여부를 리턴한다. - is - Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.
  1. .is( selector )
  2.  
  3. $('ul').click(function(event) {
      if ($(event.target).is('li') ) {
        $(event.target).css('background-color', 'red');
      }
    });
  • is 메서드는 확장된 집합에 인자로 받은 selector와 일치하는 엘리먼트가 있는지 여부를 알려 주는 메서드 이다. 위 코드는 event.target 이 li 인지를 확인하는 코드이다. 

HTML 코드 삽입하기 - html - Get the HTML contents of the first element in the set of matched elements.
  1. $('div.demo-container')
      .html('<p>All new content. <em>You bet!</em></p>');

    $('div.demo-container').html(function() {
      var emph = '<em>' + $('p').length + ' paragraphs!</em>';
      return '<p>All new content for ' + emph + '</p>';
    });

  • html() 은 해당 앨리먼트의 contents의 모두 리턴하고 .html('코드') 은 해당 앨리먼트에 콘텐츠로 설정한다. 

HTML 컨텐츠 설정하기 - text - Get the combined text contents of each element in the set of matched elements, including their descendants.
  1. var str = $("p:first").text();


    $('ul li').text(function() {
      return 'item number ' + ($(this).index() + 1);
    });

  • 혹 이쯤 되면 느낌이 오시나요! text 와 html 은 거진 동일하다. 둘다 앨리먼트의 contents를 가져오는 것인데 html은 html코드까지 얻어 오는 반면 text는 contents의 text 값만 얻어 온다. 아래 예제를 보면 단번에 "아~~~~~~" 하게 될것이다.

http://gisung2.cafe24.com/jquery/study/text1_1.jsp 

앨리먼트 더하고 빼고 지지고 복고^^; - append() - Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  1. A.append( content )
    A.append( function(index, html) )
  2. 이런 응용이 가능 하겠죠
  3. $('.container').append($('h2'));
  • 이름만 들어도 느낌이 또 오실 것입니다. append 는 A에 인자로 받은 content를 추가 하가 됩니다. 인자로 function을 사용 가능하며 function의 인자로 index 

엘리먼트 이동하기 - .appendTo() - Insert every element in the set of matched elements to the end of the target.
  1. A.appendTo( target )
  2. $('h2').appendTo($('.container'));
  • appendTo 는 append와 그 역할이 비슷하다. 하지만 append 는 A.에 content를 더하는 반면 appendTo 는 target에 A를 더한다.

http://gisung2.cafe24.com/jquery/study/appendTo1_1.jsp

 

append 와 appendTo의 역할은 거진 동일하다. 하지만  target 과 content 열할을 하는 위치가 다르니 꼭 주의하기 바란다. 또 앨리먼트 하나만 이동시킬 경우는  appendTo가 좀더 편하다고 한다.

중요한것은 append 와 appendTo 는 target의 수에 따라 == selector을 통해 반환한 앨리먼트가 한개이면 이동을 하고 한개 이상이면 복사를 한다는 것이다.

http://gisung2.cafe24.com/jquery/chapter3/lab.move.and.copy.html

  • 위 예제를 통해서 제대로 이해하고 넘어갔으면 좋겠다. 왜? 자주 쓰일것 같아서 이다^^;

값 얻어 오기 또 넣어주기 - val() - Get the current value of the first element in the set of matched elements.
  1. $("#single").val();

    $('select.foo option:selected').val();    // get the value from a dropdown select
    $('select.foo').val();                    // get the value from a dropdown select even easier
    $('input:checkbox:checked').val();        // get the value from a checked checkbox
    $('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

  • 엘리먼트의 값을 얻어 오는 메서드이다. 값 뿐만 아니라 :selected,  :checked 셀렉터를 함께 사용하면 장점이 극대화 된다.

http://gisung2.cafe24.com/jquery/study/val1_1.jsp

이와는 반대로 값을 넣을 수 도 있다.

  1. .val( value )

    $('input:text.items').val(function(index, value) {
       return value + ' ' + this.className;
    });
  • 위와 같이 값을 설정할 수 있다.

http://gisung2.cafe24.com/jquery/study/val1_2.jsp 

이전 확장 집합으로 돌아 가기 - end() - End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
  1. <!DOCTYPE html>
    <html>
    <head>
      <style>p { margin:10px; padding:10px; }</style>
      <script src="/scripts/jquery-1.4.js"></script>
    </head>
    <body>
        <p><span>Hello</span>, how are you?</p>
       <script>

    $("p").find("span").end().css("border", "2px red solid");

    </script>

    </body>
    </html>

  • 장문에 jQuery 코딩을 하다 보면 자주 사용하게 될것이다^^;(제생각임) 커맨드 체인을 이용하여 확장집합을 변형 시킬때. end()를 사용함으로써 이전 확장 집합으로 되돌아 갈 수 있는 것이다.

http://gisung2.cafe24.com/jquery/study/end1_1.jsp 

찾아라 - index() - Search for a given element from among the matched elements.
  1. <!DOCTYPE html>
    <html>
    <head>
      <style>div { font-weight: bold; color: #090; }</style>
      <script src="/scripts/jquery-1.4.js"></script>
    </head>
    <body>
       <ul>
         <li id="foo">foo</li>
         <li id="bar">bar</li>
         <li id="baz">baz</li>
       </ul>
    <div></div>
    <script>

        var listItem = $('#bar');
        $('div').html( 'Index: ' + $('li').index(listItem) );</script>
    </body>
    </html>

  • 화면엔 "Index: 1" 가 출력 된다. 먼저 셀렉터로 확장 집합을 만들고 해당 엘리먼트가 몇번째 인지 리턴한다. 없으면 -1 이다^^; 

확장집합 필터링 하기 - filter() - Reduce the set of matched elements to those that match the selector or pass the function's test.
  1. $('li').filter(function(index) {
      return $('strong', this).length == 1;
    }).css('background-color', 'red');


    $('li').filter(function(index) {
      return index % 3 == 2;
    }).css('background-color', 'red');
  • 제법 괜찮은 놈임에는 틀림이 없다. 확장집합을 필터링 한다. function을 실행하여 false를 리턴한 엘리먼트는 제거 된다.

http://gisung2.cafe24.com/jquery/study/filter1_1.jsp

http://gisung2.cafe24.com/jquery/study/filter1_2.jsp

  • 왠지 이놈은 자주 쓸것 같다! 자주 쓰면 나쁠것 같긴 하지만! 흠..(제생각)

  1. this.innerHTML.match('^\d+$/');
  • 이런식으로 filter 안 function 에서 match를 사용하여 text 와 정규식이 일치하는 엘리먼트가 있다면 선택 할 수 있다. 
확장 집합에 일부 부분 집합을 리턴한다. - slice() - Reduce the set of matched elements to a subset specified by a range of indices.
  1. <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>

    $('li').slice(2).css('background-color', 'red');

    $('li').slice(2, 4).css('background-color', 'red');

  • 선택된 확장집합에서 연속된 일부 특정 영역을 리천한다. ps. slice(포함됨, 미포함됨); 0부터 시작함 

http://gisung2.cafe24.com/jquery/study/slice1_1.jsp 

존재하는가? 일치하는가? - is() - Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.
  1. <ul>
      <li>list <strong>item 1</strong></li>
      <li><span>list item 2</span></li>
      <li>list item 3</li>
    </ul>


    $('ul').click(function(event) {
      if ($(event.target).is('li') ) {
        $(event.target).css('background-color', 'red');
      }
    });

  • 확장집합.is(셀렉터) 와 같은 형식으로 확장집합과  인자로 넘어온 셀렉터에의해 반환된 집합이 일치하면 true 그렇지 않다면 false를 리턴한다. 

복사본을 리턴하라 - clone() - Create a copy of the set of matched elements.
$('.hello').clone().appendTo('.goodbye');
  • 위와 같이 clone()를 사용하면 첫번째 셀렉터에 의해 선택된 .hello 라는 클래스를 사용하는 집합이 .goodbye에 더해지는 것이 아니라 .hello 집합의 복사본이 이동 또는 복사 되어 진다.

http://gisung2.cafe24.com/jquery/study/find1_1.jsp 

원본 집합에서 검색 조건 셀렉터와 일치하는 새로운 집합을 리턴 - find() - Get the descendants of each element in the current set of matched elements, filtered by a selector.
  • <!DOCTYPE html>
    <html>
       <head>
         <script src="/scripts/jquery-1.4.js"></script>
       </head>
       <body>
           <p><span>Hello</span>, how are you?</p>
           <p>Me? I'm <span>good</span>.</p>
           <script>
               $("p").find("span").css('color','red');
            </script>
        </body>
    </html>
  • 타이틀 그대로 입니다. 선택되어진 확장 집합에서 find에 인자로 넘어온 셀렉터와 일치하는 집합만 리턴한다는 것 입니다^^; 제법 유용 하겠네요!

http://gisung2.cafe24.com/jquery/study/find1_1.jsp 

기타 메서드

$(window).width();   // returns width of browser viewport
$(document).height(); // returns width of HTML document
 
$("#getp").click(function () {
  $("p").width(30);
});

  • 엘리먼트의 가로 세로 크기를 얻어 온다.

 

 

 

+ Recent posts