jQuery 기초

jhree333·2023년 11월 11일

jQuery

목록 보기
1/4
<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
  </head>
  <body>
    <h1 id="main-heading">What is jQuery?</h1>

    <p>jQuery is the most popular JavaScript library.</p>

    <h1>Why should you learn jQuery?</h1>

    <p class="note">Note: jQuery functions use the DOM API (like <code>document.getElementById</code>).</p>

    <!-- CDN 방식으로 jQuery를 사용할 수도 있다. -->
    <!-- https://developers.google.com/speed/libraries/#jquery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>
const elem = document.getElementsByTagName('h1');
for (let i = 0; i < elem.length; i++) {
  elem[i].textContent = 'Hello';
}

//jQuery
// app.js
$('h1').text('Hello');

jQuery 함수

  • jQuery를 사용하기 위해서는 먼저 jQuery 객체를 생성하여야 함.
  • 생성된 jQuery 객체는 다양한 메소드를 가지는데 jQuery를 학습한다고 하는 것은 대체로 이 메소드를 사용하는 방법을 익히는 것.
  • jQuery 객체를 생성하기 위해서는 jQuery 함수를 사용.
jQuery()
  • jQuery() 함수를 축약형(Shorthand)으로 기술하면 다음과 같음.
$()
  • jQuery() 함수는 전달되는 인수의 종류에 따라 다른 움직임을 하지만 결국 jQuery 객체를 반환.

CSS 스타일의 selector를 인수로 전달받을 때

  • jQuery는 CSS 스타일의 selector를 이용하여 요소를 선택할 수 있음
jQuery('h1');
  • 축약형(Shorthand)으로 기술하면 다음과 같음
$('h1');
  • text() 메소드는 jQuery 객체가 제공하는 메소드로 해당 요소(Matched set)의 텍스트를 반환.
$('h1').text();
// 텍스트를 변경하는 방법은 아래와 같이 사용.
$('h1').text('Hello!');

HTML을 인수로 전달받을 때

  • HTML 문자열을 인수로 받으면 새로운 HTML 요소를 생성
$('<p id="test">My <em>new</em> text</p>').appendTo('body');

JavaScript 객체를 인수로 전달받을 때

  • JavaScript 객체(plain object, DOM element, array 등)를 인수로 받으면 그 객체를 jQuery 객체로 wrap한 객체를 반환.
$('div.foo').click(function () {
  $(this).slideUp();
});

// Define a plain object
const foo = { foo: 'bar', hello: 'world' };

// Pass it to the jQuery function
const $foo = $(foo);

// Accessing property values
const test1 = $foo.prop('foo');
console.log(test1); // bar

// Setting property values
$foo.prop('foo', 'foobar');

// Accessing property values
const test2 = $foo.prop('foo');
console.log(test2); // foobar

콜백함수를 인수로 전달받을 때

  • 안전하게 DOM을 조작하기 위해서는 DOM이 완전히 로드된 후 자바스크립트가 실행되는 것이 바람직한데 이를 위해 이벤트 처리가 필요.
jQuery(document).ready(function () {
  // Do something...
});

// Shorthand for jQuery(document).ready()
$(document).ready(function () {
  // Do something...
});

// Shorthand for $(document).ready()
$(function () {
  // Do something...
});

// js/app.js
$(function () {
  $('h1').text('Hello!');
});

Selector

  • jQuery는 CSS 스타일의 Selector를 이용하여 요소를 선택할 수 있음. 이것은 자바스크립트 DOM API보다 쉽고 강력하며 유연.

태그 / ID / Class 선택자

  • 자바스크립트의 document.getElementsByClassName(class) 메소드 등을 사용하여 선택한 요소들(HTMLCollection)에 개별적으로 접근하기 위해서는 반복문을 사용하여야 함.
  • 이때 getElementsByClassName 메소드가 반환하는 HTMLCollection이 실시간으로 Node의 상태 변경을 반영하기 때문에 경우에 따라(예를 들어 클래스명이 변경될 때) 반복문을 역방향으로 돌리는 등 번거로운 처리가 필요.
  • jQuery는 반복문 없이 해당하는 모든 요소에 접근/조작할 수 있음. 이를 묵시적 반복(implicit iteration).
  • 여러 개의 요소를 선택하여 봄. CSS 스타일의 Tag Selector를 사용하여 li 요소 3개를 선택하고 이 요소들의 텍스트를 일괄 변경.
<!DOCTYPE html>
<html>
  <head>
    <title>jQuery</title>
  </head>
  <body>
    <h1>Where do you want to go?</h1>
    <h2>Travel Destinations</h2>
    <p>Plan your next adventure.</p>
    <ul id="destinations">
      <li>Rome</li>
      <li>Paris</li>
      <li class="promo">Rio</li>
    </ul>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
      $(function () {
        console.log($('li'));
        // [li, li, li.promo, prevObject: n.fn.init(1), context: document, selector: "li"]
        $('li').text('Orlando');
      });
    </script>
  </body>
</html>
// Tag Selector
$('li');

// ID Selector
$('#container');

// Class Selector
$('.articles');

후손 선택자 (Descendant Selector)

      $(function () {
        $('#destinations .promo').text('Orlando');

        // var el = document.querySelectorAll('#destinations .promo');
        // for (var i = 0; i < el.length; i++) {
        //   el[i].textContent = 'Orlando';
        // }
      });

자식 선택자 (Child Selector)

   $(function () {
        $('#destinations > li').text('Orlando').css('color', 'red');

        // var el = document.querySelectorAll('#destinations > li');
        // for (var i = 0; i < el.length; i++) {
        //   el[i].textContent = 'Orlando';
        //   el[i].style.color = 'red';
        // }
      });

복합 선택자

 $(function () {
        $('#france > li, .promo').text('Orlando');

        // var el = document.querySelectorAll('#france > li, .promo');
        // for (var i = 0; i < el.length; i++) {
        //   el[i].textContent = 'Orlando';
        // }
      });

가상 클래스 선택자

     $(function () {
        $('#destinations li:first').css('color', 'red');
        $('#destinations li:last').css('color', 'blue');
        // $('#destinations li:odd').css('color', 'orange');
        // $('#destinations li:even').css('color', 'purple');

        // var el = document.getElementById('destinations');
        // console.log(el.firstChild);
        // console.log(el.lastChild);

        // el.firstChild.style.color = 'red';
        // el.lastChild.style.color = 'blue';
      });

Traversing

  • Selector를 사용하여 matched set을 생성한 이후, matched set의 요소들과 관련있는 다른 요소에 접근할 수 있다. 이를 DOM 탐색(DOM Traversing).
  $(function () {
        const el1 = $('#destinations li');         // Descendant Selector
        const el2 = $('#destinations').find('li'); // Traversing

        console.log(el1);
        // [li, li, li.promo, prevObject: n.fn.init(1), context: document, selector: "#destinations li"]
        console.log(el2);
        // [li, li, li.promo, prevObject: n.fn.init(1), context: document, selector: "#destinations li"]
      });

Manipulation

  • DOM에 새로운 요소를 추가/삭제, 복사, 속성 변경 등을 실시할 수 있다. 이를 DOM 조작(DOM Manipulation).

Appending

    $(function () {
        let price = $('<p>From $399.99</p>');
        $('.vacation').append(price);
      });
DOM에 콘텐츠를 삽입할 때, 위치를 지정할 수 있음. 이때 사용할 수 있는 메소드는 4가지.

append() : 선택 요소의 닫는 태그 앞에 콘텐츠를 삽입.

prepend() : 선택 요소의 여는 태그 뒤에 콘텐츠를 삽입.

after() : 선택 요소의 뒤에 콘텐츠를 삽입.

before() : 선택 요소의 앞에 콘텐츠를 삽입.

Removing

  • 요소의 제거는 remove() 메소드를 사용.
  $(function () {
        let price = $('<p>From $399.99</p>');
        $('.vacation').append(price);
        $('button').remove();
      });

Event

  • 매치드셋에 이벤트를 바인딩하고 해당 이벤트가 발생했을 때 실행될 콜백 함수를 지정.
     $(function () {
        $('button').on('click', function () {
          let price = $('<p>From $399.99</p>');
          $(this).closest('.vacation').append(price);
          $(this).remove();
        });
      });
profile
안녕하세요.

0개의 댓글