본문 바로가기
자바스크립트와 캔버스

jQuery 함수 ( prototype ) 추가

반응형

자바스크립트에 프로토 타입이 있듯이 jQuery 에도 프로토 타입이 있습니다.

바로 $.fn 사용자 정의 프로토타입 기능인데요.

간단히 말해 jQuery 함수를 직접 추가할 수 있다는 의미입니다.

jQuery 프로토타입은 보통 다음과 같이 선언이 가능합니다.

$.fn.메소드명 = function(파라미터){
	$(this).each(function(){
		: // 처리할코드
	});
};

그러면 다음과 같이 사용할 수가 있지요.

$('css셀렉터').메소드명(파라미터);

한번 예제를 볼까요?

아래 예제는 3개의 div 의 class 이름이 모두 CrayTest 입니다.

<!DOCTYPE html>
<html>
	<head>
	<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
	<script>
	$.fn.CrayCss = function(color){
		$(this).each(function(){
			$(this).css('border', color + ' solid 1px');
		});
	};
	</script>
	</head>
	<body>
		<div class=CrayTest>하나</div>
		<div class=CrayTest>둘</div>
		<div class=CrayTest>셋</div>

		<input type=button value="빨강" onclick="$('.CrayTest').CrayCss('red');">
		<input type=button value="파랑" onclick="$('.CrayTest').CrayCss('blue');">
		<input type=button value="녹색" onclick="$('.CrayTest').CrayCss('green');">
	</body>
</html>

그리고 3개의버튼이 마련되어 있지요.

빨강 버튼을 클릭해볼까요?

엇, div 요소 3개 모두 경계선 색상이 빨강 색으로 바뀌었습니다.

파랑과 녹색도 마찬가지로 각각의 색상으로 바뀌는데요.

버튼을 누를 때 실행되는 jQuery 함수는 $('.CrayTest').CrayCss('red'); 입니다.
CrayCss라는 jQuery 함수는 원래 jQuery 에 존재하지 않지만,
별도로 정의했기 때문에 사용할 수 있는 것이지요.

정의된 부분은 아래와 같습니다.

$.fn.CrayCss = function(color){
	$(this).each(function(){
		$(this).css('border', color + ' solid 1px');
	});
};

$.fn.CrayCss = function 이 부분은

CrayCss 라는 jQuery 함수를 새로 추가하겠다는 말입니다.

그리고 뒤에 따라붙는 (color)는 함수사용시 파라미터를 의미하구요.

아래와 같이 묶은 부분은 함수 사용시 넘겨받을 하나하나의 요소를 따로 처리할때 사용하는 기능입니다. 본 예제에서는 div 가 3개니까 3번 작동됩니다.

$(this).each(function(){

:

});

다음으로 경계선을 변경하는 css 부분인데요.

color 변수값을 참조해서 각각 div 의 색상을 변경합니다.

$(this).css('border', color + ' solid 1px');

착오없으실 부분은 each 안에서 $(this)가 사용될 경우,

처음에 함수를 호출할때 사용되는 .CratTest 클래스가 아니라

div 하나하나 각각의 요소를 의미합니다.

코드를 하나 더 추가해서 확인해볼까요?

<!DOCTYPE html>
<html>
	<head>
	<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
	<script>
	$.fn.CrayCss = function(color){
		var number =1;
		$(this).each(function(){
			$(this).css('border', color + ' solid 1px');
			$(this).text( $(this).text() + " - " + number );
			number++;
		});
	};
	</script>
	</head>
	<body>
		<div class=CrayTest>하나</div>
		<div class=CrayTest>둘</div>
		<div class=CrayTest>셋</div>

		<input type=button value="빨강" onclick="$('.CrayTest').CrayCss('red');">
		<input type=button value="파랑" onclick="$('.CrayTest').CrayCss('blue');">
		<input type=button value="녹색" onclick="$('.CrayTest').CrayCss('green');">
	</body>
</html>
 변경된 부분은 number 값이라는 요소가 추가된 것 뿐인데요.

$.fn.CrayCss = function(color){
		var number =1;
		$(this).each(function(){
			$(this).css('border', color + ' solid 1px');
			$(this).text( $(this).text() + " - " + number );
			number++;
		});
	};

버튼을 누르면 다음과 같이 작동합니다.

number 라는 변수가 1씩 증가하면서 각각의 div 요소에 숫자를 붙여주기 때문이지요 :)

오늘도 방문하시고 글 읽어주셔서 감사합니다 :)

반응형