CatsWhoCode 게시물의 팁과 실제 사례입니다.
문서가 "준비"될 때까지 페이지를 안전하게 조작할 수 없습니다. 이러한 이유로 우리 개발자들은 모든 JS 코드를 jQuery $(document).ready()
함수 안에 래핑하는 습관을 들였습니다.
$ ( document ) . ready ( function ( ) {
console . log ( 'ready!' ) ;
} ) ;
순수 JavaScript를 사용하면 동일한 결과를 쉽게 얻을 수 있습니다.
document . addEventListener ( 'DOMContentLoaded' , function ( ) {
console . log ( 'ready!' ) ;
} ) ;
이벤트 리스너는 JavaScript 개발에서 매우 중요한 부분입니다. jQuery에는 이를 처리하는 매우 쉬운 방법이 있습니다.
$ ( someElement ) . on ( 'click' , function ( ) {
// TODO event handler logic
} ) ;
JavaScript에서 이벤트 리스너를 생성하는 데에는 jQuery가 필요하지 않습니다. 방법은 다음과 같습니다.
someElement . addEventListener ( 'click' , function ( ) {
// TODO event handler logic
} ) ;
jQuery를 사용하면 ID, 클래스 이름, 태그 이름 등을 사용하여 요소를 매우 쉽게 선택할 수 있습니다.
// By ID
$ ( '#myElement' ) ;
// By Class name
$ ( '.myElement' ) ;
// By tag name
$ ( 'div' ) ;
// Children
$ ( '#myParent' ) . children ( ) ;
// Complex selecting
$ ( 'article#first p.summary' ) ;
순수 JavaScript는 요소를 선택하는 다양한 방법을 제공합니다. 아래의 모든 방법은 IE8+뿐만 아니라 모든 최신 브라우저에서 작동합니다.
// By ID
document . querySelector ( '#myElement' ) ;
// By Class name
document . querySelectorAll ( '.myElement' ) ;
// By tag name
document . querySelectorAll ( 'div' ) ;
// Children
document . querySelectorAll ( 'myParent' ) . childNodes ;
// Complex selecting
document . querySelectorAll ( 'article#first p.summary' ) ;
대부분이 알고 있듯이 Ajax는 비동기 웹 애플리케이션을 생성할 수 있는 기술 집합입니다. jQuery에는 아래와 같이 get()
포함하여 Ajax에 유용한 메소드 세트가 있습니다.
$ . get ( 'ajax/test.html' , function ( data ) {
$ ( '.result' ) . html ( data ) ;
alert ( 'Load was performed.' ) ;
} ) ;
jQuery를 사용하면 Ajax 개발이 더 쉽고 빨라지지만 Ajax를 사용하기 위해 프레임워크가 필요하지 않다는 것은 확실합니다.
var request = new XMLHttpRequest ( ) ;
request . open ( 'GET' , 'ajax/test.html' , true ) ;
request . onload = function ( e ) {
if ( request . readyState === 4 ) {
// Check if the get was successful.
if ( request . status === 200 ) {
console . log ( request . responseText ) ;
} else {
console . error ( request . statusText ) ;
}
}
} ;
요소의 클래스를 추가하거나 제거해야 하는 경우 jQuery에는 이를 수행하는 두 가지 전용 메서드가 있습니다.
// Adding a class
$ ( '#foo' ) . addClass ( 'bold' ) ;
// Removing a class
$ ( '#foo' ) . removeClass ( 'bold' ) ;
jQuery가 없으면 요소에 클래스를 추가하는 것은 매우 쉽습니다. 클래스를 제거하려면 replace()
메서드를 사용해야 합니다.
// Adding a class
document . getElementById ( 'foo' ) . className += 'bold' ;
// Removing a class
document . getElementById ( 'foo' ) . className = document . getElementById ( 'foo' ) . className . replace ( / ^bold$ / , '' ) ;
jQuery가 왜 그렇게 인기가 있는지에 대한 실제적인 예는 다음과 같습니다. 요소를 페이딩하는 데는 한 줄의 코드만 사용됩니다.
$ ( el ) . fadeIn ( ) ;
순수한 JavaScript에서도 똑같은 효과를 얻을 수 있지만 코드가 훨씬 길고 복잡합니다.
function fadeIn ( el ) {
el . style . opacity = 0 ;
var last = + new Date ( ) ;
var tick = function ( ) {
el . style . opacity = + el . style . opacity + ( new Date ( ) - last ) / 400 ;
last = + new Date ( ) ;
if ( + el . style . opacity < 1 ) {
( window . requestAnimationFrame && requestAnimationFrame ( tick ) ) || setTimeout ( tick , 16 ) ;
}
} ;
tick ( ) ;
}
fadeIn ( el ) ;
요소를 숨기고 표시하는 것은 매우 일반적인 작업입니다. jQuery는 요소 표시를 수정하기 위한 hide()
및 show()
메서드를 제공합니다.
// Hiding element
$ ( el ) . hide ( ) ;
// Showing element
$ ( el ) . show ( ) ;
순수 JavaScript에서는 요소를 표시하거나 숨기는 것이 더 이상 복잡하지 않습니다.
// Hiding element
el . style . display = 'none' ;
// Showing element
el . style . display = 'block' ;
jQuery로 DOM을 조작하는 것은 매우 쉽습니다. #container
에 <p>
요소를 추가하고 싶다고 가정해 보겠습니다.
$ ( '#container' ) . append ( '<p>more content</p>' ) ;
순수 JavaScript로 그렇게 하는 것도 그다지 큰 문제가 아닙니다.
document . getElementById ( 'container' ) . innerHTML += '<p>more content</p>' ;