다연이네

[days02] 복습 - on()/off() 이벤트 연결/제거 본문

Web/jQuery

[days02] 복습 - on()/off() 이벤트 연결/제거

 다연  2020. 12. 21. 18:55
반응형

$(selector).on(이벤트명, 이벤트핸들러);
$(선택자).on({이벤트명:이벤트핸들러, 이벤트명:이벤트 핸들러}); => 중괄호 : 이벤트를 여러개 연결

 

 

<script>

$(function() {
	$("#demo")
   	 .on('click', function(event) {
		$(this).css('background','red');})
   	 .on("mouseover", function(event) {
		$(this).css('background','blue');})
   	 .on("mouseout", function(event) {
		$(this).css('background','orange');})
});        
</script>

위처럼 하지 않고 on을 1번만 쓴 후 중괄호로 묶어도 된다.

<script>
$(function() {
	$("#demo")
	  .on({ 
          click:function(event) {
              $(this).css('background','red');
          },
          mouseover:function(event) {
              $(this).css('background','blue');
          },
          mouseout: function(event) {
              $(this).css('background','orange');
          }
	})
});

</script>

 

 

 기본 이벤트 제거 

event.preventDefault();  //기본 이벤트 제거
event.stopPropagation(); //버블링 제거 (stop 전파)

<body>
<a href="http://www.naver.com">naver</a>

<script>
	$(function() {
		$("a").on("click", function(event) {
			alert("문서 이동합니다");
			//기본 이벤트 제거
			//event.preventDefault();
			//event.stopPropagation();
			
			//위 두줄 코딩과 같은 의미
			return false;
		})
	});
</script>
</body>

위 코딩은 a태그를 눌러도 링크로 이동하지 않고 alert만 뜬 후 아무 일도 일어나지 않는다.

기본 이벤트를 제거했기 때문이다.

 

활용 예시2

<script>
//이벤트를 연결합니다
$(function() {
	//이벤트를 연결합니다.
	$('form').submit(function(event) {
		//input 태그 값을 추출
		var value = $('input').val();
		
		//유효성 검사
		if(value.replace(/[가~힣]/g, '').length ==0){
			//검사 통과
			alert("과정을 진행합니다");
		}else{
			alert("한글 이름을 입력해주세요");
			event.preventDefault();
		}
	});
});
</script>
</head>
<body>

<form>
<label>이름</label>
<input type="text" />
<input type="submit" />
</form>

</body>

 

반응형
Comments