본문 바로가기
Development (국비 복습 )/JavaScript

[jQuery]$(this)의 활용

by Puddingforever 2023. 2. 15.

 

 

주로 동일한 소스가 반복되는 곳에서 많이 사용한다 (메뉴탭)

자기가 원하는 타겟만 변할 수 있게 해줌 

 

	$(document).ready(function(){
    	$(.buttons).click(function(){
        	$(this).val("눌렀음");
        });
    });

    <input type="button" class="buttons" value="버튼" />
    <input type="button" class="buttons" value="버튼" />
    <input type="button" class="buttons" value="버튼" />

이렇게 소스코드를 적으면 ,  일일이 class마다 타입을 다르게 하여 코드를 작성할 필요가 없다.

예시)

만약 클라스를 각각 다르게 했다면..아래처럼 비효율적으로 코드를 작성했을 것이다. 

<script>
$(document).ready(function(){
	$(".buttons1").click(function(){
    	$(".buttons1").val("눌렀음");
    });
});

$(document).ready(function(){
	$(".buttons2").click(function(){
   		$(".buttons1").val("눌렀음"); 
    });
});
</script>
<input type="button" class="buttons1" value="버튼1" />
<input type="button" class="buttons2" value="버튼2" />

 

 

 

 

 

 

 

 

 

 

참고

https://wonjuman.tistory.com/20

댓글