본문 바로가기

My list/jQuery

jQuery 기본

 

1. $()

1) $()란?

이름이 $인 함수를 호출한 것.

$("div").css("border","4px solid #000");
jQuery("div").css("border","4px solid #000");

 둘은 같은 코드이다.

 

2) $()함수의 리턴값

$("div").css("border","4px solid #000");

위의 코드를 좀 더 보기 쉽게 정리한다면

var $divs = $("div");
$divs.css("border", 4px solid #000);

다음과 같이 표현할 수 있다.

 

https://api.jquery.com/jquery/

 

jQuery() | jQuery API Documentation

Description: Creates DOM elements on the fly from the provided string of raw HTML. Creating New Elements If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is i

api.jquery.com

위 페이지에서 jQuery의 다양한 래퍼런스들 확인 가능.

 

2. jQuery

<script> 
$(document).ready(function() { 

// 메뉴 항목 추가1 
$("#menu").append("<li>newmenu1</li>"); 

// 메뉴 항목 추가2 
$("#menu").append("<li>newmenu2</li>"); 

// 메뉴에 border 속성 설정 
$("#menu").css("border", "1px solid #f00"); }) 
</script>

 

 

<script> 
$(document).ready(function() { 

var $menu = $("#menu"); 

// 메뉴 항목 추가1 
$menu.append("<li>newmenu1</li>"); 

// 메뉴 항목 추가2 
$menu.append("<li>newmenu2</li>"); 

// 메뉴에 border 속성 설정 
$menu.css("border", "1px solid #f00"); }) 
</script>

위 코드를 보면 $("#menu"); 를 3번 호출한 반면 아래 코드를 보면 딱 한번 호출한 것을 확인.

가장 간단하면서도 효과적인 jQuery최적화 방법