본문 바로가기

jQuery

jQuery

jQuery란

jQuery는 자바스크립트 라이브러리로서 더 심플하고 쉬운 자바스크립트 코딩이 가능하게 해준다.

 

jQuery 라이브러리는 다음을 포함한다

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

jQuery는 두가지 버전이 있고 모두 jQuery.com 에서 다운 받을 수 있다.

<head> 섹션 안의 <script> 태그로 jQuery  라이브러리를 추가할 수 있다.

또한 별도의 파일에 jQuery 함수들을 모아 한번에 적용시킬수도 있다

 

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>

 

jQuery Syntax

jQuery 문법은 html 요소를 선택하고 그것에 대한 action을 행하게 하는 구성으로 이루어져있다

 

$(selector).action()

 

ex) html에서 사용했던 id, class, tag들을 한번에 지정하여 사용할 수 있는것

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

 

Document Ready Event

문서가 다 로딩이 되기 전에 작업을 수행하는것을 방지하기 위해 ready 이벤트를 활용하는것이다.

ready event 사용으로 문서가 완전히 로딩 된 후 작업할 수 있게한다.

다만 페이지가 로드되기 전에 수행해야하는 작업들이 있다면 주의해서 사용해야한다

 

$(document).ready(function(){

  // jQuery methods go here...

});

jQuery Selectors

element selector : 이름에 기반하여 요소를 선택하게 되어있다

ex) $("p") : <p> 태그의 모든 요소를 선택함

 

#id selector : id를 사용하여 요소를 선택함

ex) $("#test") : test의 id를 가진 모든 요소를 선택함

 

.class selector : class를 사용하여 요소를 선택함

ex) $(".abc") : abc 클래스에 해당하는 모든 요소를 선택

 

그 외에도 여러 selector들이 있다

$("*") : Selects all elements
$(this) : Selects the current HTML element
$("p.intro") : Selects all <p> elements with class="intro"
$("p:first") : Selects the first <p> element
$("ul li:first") : Selects the first <li> element of the first <ul>
$("ul li:first-child") : Selects the first <li> element of every <ul>
$("[href]") : Selects all elements with an href attribute
$("a[target='_blank']") : Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") : Selects all <a> elements with a target attribute value NOT equal to "_blank"
$(":button") : Selects all <button> elements and <input> elements of type="button"
$("tr:even") : Selects all even <tr> elements
$("tr:odd") : Selects all odd <tr> elements

jQuery Event Methods

웹페이지가 응답할 수 있는 다양한 visitor의 action을 Event라고 한다

 

Common DOM events:

Mouse Events Keyboard Events Form Events Document/Window Events
click  keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave   blur unload

 

이런 이벤트들에 대한 jQuery의 문법예시는 다음과 같다

 

$("p").click(function(){
  // action goes here!!
});

 

on() : method attaches one or more event handlers for the selected elements.

하나의 요소에 대해 여러개의 이벤트 적용시 사용할 수 있다

 

$("p").on({
  mouseenter: function(){
    $(this).css("background-color", "lightgray");
  },
  mouseleave: function(){
    $(this).css("background-color", "lightblue");
  },
  click: function(){
    $(this).css("background-color", "yellow");
  }
});