jQuery/기초

jQuery 기초

carrot62 2020. 7. 30. 13:53

jQuery 는 자바스크립트 라이브러리이다. 이전에 자바스크립트를 통해서 하던 작업들을 훨씬 더 짧은 코드로, 간편하게 만들 수 있다는 장점을 가지고 있다.

jQuery를 이용해서 다음과 같은 작업들을 할 수 있지만 BOM(Browser Object Model)과 관련된 작업은 여전히 자바스크립트로 처리해야 한다.

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

jQuery를 사용하기

jQuery는 앞서 말했듯이 JS의 라이브러리이기 때문에 반드시 jQuery 라이브러리 추가하는작업을 해줘야 한다.
jQuery에도 많은 버전이 있으니 사용하기에 앞서 버전을 잘 확인하도록 하자!

  • jQuery 라이브러릴 다운 받아서, 서버에 올린 후 작업하거나
  • jQuery CDN(Content Delivery Network)을 이용해서 링크로 빠르게 접속해서 사용할 수 있는 방법도 있다.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

jQuery 기본 문법

Selectors

이전에 CSS에서 사용하던 selectors 에 $( selector )만 덧붙여주면 된다.

CSS Selectors jQuery
p $("p")
#id $("#id")
.classname $(".classname")
p#userid $("p#id")
* $("*")
this (현재 element를 선택한다) $(this)

이외에도 jQuery에서의 다른 selectors 선택하는 방법:

출처: https://www.w3schools.com/jquery/jquery_selectors.asp

jQuery selectors를 이용하면 좋은 점

Selectors를 사용해야 할때 코드 훨씬 짧고 간편해졌다는 것!

document.getElementById("demo").	//using javascript
$("#id")	//using jQuery

Document ready event

아래에 제시된 두 방법은 동일하다.

$(document).ready(function(){

  // jQuery methods go here...

});

//또는

$(function(){

  // jQuery methods go here...

});

페이지가 다 로딩 된 이후에 event가 작동하도록 설정하는 방법:

  • 제일 밑에 <script> 를 작성
  • <body onload="">
  • window.load() 또는 documnet.body.addEventListener('load', function); 사용

하지만 jQuery를 사용하면 ready function (로딩이 다 된 이후에 jQuery code가 실행 될 수 있도록 해준다)을 이용해서 이 작업을 훨씬 간단하게 실행할 수 있다.

예시) 버튼을 누르면 paragraph를 숨기는 기능

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me to hide paragraphs</button>

</body>
</html>

jQuery 함수가 많아지면 .js 파일에 따로 모아놔서 <head> 부분에 <script>로 추가해놓고 사용하기도 한다.

<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>

 

예제 실습: http://songoftea.dothome.co.kr/2020Camp/jsql_hw1_1.html

 

Document

2020/07/30 WebService Camp: jQuery tutorial Using jQuery Selectors This is a heading This is a paragraph. This is another paragraph. Click me to hide paragraphs Using jQuery Events If you "DOUBLE" click on me, I will disappear. Click me away! Click me too!

songoftea.dothome.co.kr