자료 저장소


http://codepen.io/clintcparker/details/KAvaG

CodePen Basic jQuery Exercise 내용을 실습하고 정리합니다.



What is $ ?


jQuery 최상위 레벨 jQuery()의 별칭입니다.

jQuery() 와 $()은 같은 기능이지만, 빠르게 작성할 수 있는 $()를  많이 사용합니다.


jQuery() 함수는 CSS selector를 사용해 DOM 요소를 선택하고 많은 작업을 수행하는 방법을 제공합니다.

완전한 크로스 브라우저 DOM traversal을 제공하고, jQuery 객체는 많은 메소드를 내장하고 있습니다.

예를 들어 현재 브라우저 환경이 지원하는 정보는 $.support 속성을 참조할 수 있고, $.ajax 메소드로 AJAX 요청을 작성할 수 있습니다.


다음 예제는 <li></li> element를 모두 선택하는 동일한 방법입니다.

1
2
var $listItems = jQuery('li');
var $listItems = $('li');
cs

관례 : jQuery 객체 앞에는 "$"를 붙입니다.



$(document).ready()


jQuery를 사용하기 전에 페이지를 조작 할 준비가 된 상태인지 확인해야 합니다.

jQuery를 사용하여 코드를 함수에 넣은 다음 $(document).ready() 에 전달하면 됩니다.

여기서 볼 수 있듯이, 함수는 익명일 수 있습니다.


또는 위와 같은 방식으로 해석되는 짧은 버전을 사용할 수 있습니다.

1
$(function() {}) 
cs


관례 : $(function() {}) 을 여러번 호출하는 것은 성능에 문제는 없지만, 한 페이지에 한번만 사용하는것이 일반적입니다.

1
2
3
$( document ).ready(function() {
  alert'ready!' );
});
cs


  

CSS Selectors and Traversal


jQuery의 주요 강점은 유효한 CSS selector를 사용하여 DOM 내의 node를 선택하고 순회하는 기능입니다.

이 기능은 Sizzle selector engine을 통해 수행합니다.

Sizzle은 CSS 스펙의 일부가 아닌 많은 selector들을 도입했습니다, 예를 들면 :not()

Sizzle은 jQuery가 알려져 있는 크로스 브라우저 지원을 제공하여,

모든 브라우저에서 완전히 지원되지 않는 많은 CSS selector를 정규화 하였습니다.


현재 객체를 반환하는 jQuery의 method 체인 기능으로 현재 래핑된 selector 세트를 쉽게 순회하고 필터링 할 수 있습니다.

이 체인기능을 사용하면 선택 범위를  좁히거나 show().hide().remove() 호출을 순차적으로 수행할 수 있습니다.

마크업 형식에 제한적으로 접근하는 경우 체이닝이 필수적입니다. (성능 문제로 인한듯)


관례 : '울트라' 체이닝이 해독이 어렵다는것은 금방 알 수 있습니다. 읽기가 어려워지면 새 행으로 옮기는것이 일반적입니다.

 

'first' 클래스를 추가하고 리스트에서 첫번째 항목 선택 하는 방법

1
2
3
4
5
$('.selector-examples li:first').addClass('first');
$('.selector-examples li:first-child').addClass('first');
$('.selector-examples li:nth-child(1)').addClass('first');
$('.selector-examples li').first().addClass('first');
$('.selector-examples li').get(0).className = 'first';
cs


'even' 클래스를 추가하고 리스트에서 짝수 항목을 선택하는 방법

1
2
3
$('.selector-examples li:odd').addClass('even');
$('.selector-examples li:nth-child(2n)').addClass('even');
$('.selector-examples li:nth-child(even)').addClass('even');
cs


'odd' 클래스를 추가하고 리스트에서 홀수 항목을 선택하는 방법

1
2
$('.selector-examples li:even').addClass('odd');
$('.selector-examples li:nth-child(odd)').addClass('odd');
cs


리스트에서 4번째 자식 항목에 리스트의 4번째 항목을 추가하고 'i-haz-neighbor' 클래스를 추가

1
2
3
$('.selector-examples li:nth-child(4)')
.add('li:eq(4)''.selector-examples')
.addClass('i-haz-neighbor');
cs


'last' 클래스를 추가하고 리스트에서 마지막 항목을 선택하는 방법

1
2
3
4
5
$('.selector-examples li:last').addClass('last');
$('.selector-examples li:last-child').addClass('last');
$('.selector-examples li').last().addClass('last');
$('.selector-examples li:nth-child(6)').addClass('last');
$('.selector-examples li').get(-1).className = 'last';
cs



'프로그래밍 > JavaScript : jQuery' 카테고리의 다른 글

Attribute와 Property의 차이  (0) 2017.02.16
CodePen Basic jQuery Exercise 2  (0) 2017.02.16
댓글 로드 중…

최근에 게시된 글