본문 바로가기

javascript/jQuery

[jQuery] 다른 라이브러리와 jQuery 사용하기


다른 자바스크립트 라이브러리등과 jQuery를 함께 사용하면 $ 별칭이 전역적 충돌이 일어날 수 있다.

(ex : prototype.js) 


이 때 익명의 자기호출 함수를 만들어 해결 할수 있다.


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>jQuery demo</title>
		
		<!--css style-->
		<style> 
			a.test {
				font-weight: bold;
			}
		</style>
	</head>
	<body>		
		
		<a href="http://jquery.com/">jQuery</a>		
		
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
		<!--jquery 로드-->
                <script src="prototype.js"></script>
		<script>			
		
		(function ($) {
			$("a").click(function(event) {
					
					$("a").addClass('test');
					
					alert("더이상 jQuery 홈페이지로 연결하지 않습니다.");
					
					$("a").removeClass('test');
					
					event.preventDefault();
					
					$('a').hide("slow");
				});			
		})(jQuery);
				
		</script>
	</body>
</html>

위의 코드처럼
(function($){
//jQuery 코딩
})(jQuery);

형태로 캡슐화를 시키면 prototyp의 $와 jQuery의 $가 충돌하지 않음을 보장하며, jQuery를 사용할 수 있다.
(해당 부분을 지우면 jQuery가 동작하지 않음을 확인할 수 있다. 23줄과 36줄을 주석처리 해보라)

다른 방법들은 여기서 확인할수 있다

참고문헌 : 실전 jQuery쿡북 (O'Reilly, Bj퍼블릭)