본문 바로가기
  • 문과생의 백엔드 개발자 성장기
|Playdata_study/JavaScript

210906_jQuery (bind, hover, find, traversal, click, key)

by 케리's 2021. 9. 6.

EVENT

 

  • mouseenter + mouseleave (마우스 포인터가 진입 + 퇴출할때 발생하는 이벤트)

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bind :: 여러개의 이벤트를 묶어주는 기능 :: mouseenter + mouseleave</title>
<style type="text/css">
	.reverse{background-color: black; color: white;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		$('h2').bind({ //bind 묶는기능 (마우스 진입,퇴출 이벤트 묶는기능)
			mouseenter:function(){ // 마우스가 특정 영역 안으로 진입했을 때 호출
				$(this).addClass('reverse');
			},
			mouseleave:function(){ // 마우스가 특정 영역 밖으로 나왔을 때 호출
				$(this).removeClass('reverse');
			}
		}); // bind
	});
</script>
</head>
<body>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
</body>
</html>

 

 

 

 

  • hover : 마우스 이벤트 포커스 2가지(moseenter, mouseleave)를 동시에 가지고 있는 함수

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hover() :: 마우스 이벤트 포커스 2가지(moseenter, mouseleave)를 동시에 가지고 있는 함수</title>
<style type="text/css">
	.reverse{background-color: black; color: hotpink;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		$('h2').hover(function(){ //mouseenter event focus
			$(this).addClass('reverse')
		}, function(){ //mouseleave event focus
			$(this).removeClass('reverse')
		}); // hover
	});
</script>
</head>
<body>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library</h2>
</body>

 

 

 

 

 

 

  • on 함수 사용하기 :: 클릭함수와 동일하지만 미래에 존재하는 요소에 적용 가능함

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	div{border:1px solid hotpink;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		// **** div 영역을 클릭하면 함수 호출되도록 선택자와 함수를 연결
		//    p 태그 부분에 <h2> HYERI HELLO </h2>
		
	 	// ===== 1. click
		$('div').click(function(){
			$('p').append('<h2> HYERI HELLO </h2>');
		});
		
	 	
	 	
		// ===== 2. bind
		$('div').bind('click',function(){
			$('p').append('<h2> HYERI HELLO </h2>');
		}); 
		
		
		
 		// ===== 3.one :: 한번만 실행 가능 
		$('div').one('click', function(){
			$('p').append('<h2> HYERI HELLO </h2>');
		}); 

 		
 		
 		// ===== 4.on
		$('div').on('click', function(){
			$('p').append('<h2> EHYERI HELLO </h2>');
		}); 
		
 		
 		
		// 처음에는 없었지만 나중에 동적으로 생성될 태그에 이벤트 적용하는 기능으로 연결 :: on()
		$('div').click(function(){
			$('#resultView').append('<h2 id=future>HYERI HELLO</h2>');
		});
		
		$('#resultView').on('click', '#future', onhello);  //#future영역을 클릭하면 onhello() 함수 호출되도록
	}); // ready
	
	function onhello(){
		alert("onhello function calling");
	}
	
</script>
</head>
<body>
	<div>
		<h1>$(selector).on()</h1>
		<p> on 함수 사용하기 :: 클릭함수와 동일하지만 미래에 존재하는 요소에 적용 가능함 </p>
	</div>
	
	<div id ="resultView"></div>
</body>
</html>

 

 

 

1,2,4 ::  p태그인 on함수 사용하기를 클릭하면 HYERI HELLO 라는 글자가 추가로 출력

 

3. one :: 한번만 실행된다.

 

 

HYERIHELLO 클릭하면 onhello가 출력된다 (alert)

 

 

 

  • hover ::  이미지에서 hover 효과 내기

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> hover()::mouseenter, mouseleave 이벤트포커스 2개를 이미 가지고 있는 함수 , 이미지에서 hover 효과 내기</title>
<style type="text/css">
	.larger{ width:200px; border:2px solid red;}
	img{ width:100px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		$('img').hover(function(){
			// find()
			// hover 이벤트가 적용된 img 태그중에서 class 값으로 h를 발견하면 addclass() 를 적용하겠다
			$(this).addClass('larger');
		}, function(){
			$(this).removeClass('larger');
		});
	});
</script>
</head>
<body>
	<h2>Bigger Image</h2>
	<img alt="" src="../image/1.jpg"><br/>
	<img alt="" src="../image/2.jpg"><br/>
	<img alt="" src="../image/3.jpg"><br/>
</body>
</html>

첫번째 사진에 마우스를 올리면 사진이 커짐

 

 

 

 

 

  • find() :: 특정한 선택자를 발견해서 함수를 적용할 때 사용함

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>find() :: 특정한 선택자를 발견해서 함수를 적용할 때 사용함</title>
<style type="text/css">
	table{
		border: 3px solid hotpink;
		width:550px;
	}
	tr, th, td{text-align:center; border:1px dotted blue; font-size:1.2em;}
	.hover{background-color:Lavender; color:#fff;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		//1. tbody 후손 중에서 tr을 선택자로 지정, hover() 함수를 연결한다.
		//2. hover() 안에서 현재 이벤트가 적용된 tr 태그 중에서 td라는 태그를 발견한다면 addClass() 적용|removeclass()적용
		$('tbody tr').hover(function(){
			$(this).find('td').addClass('hover');
		}, function(){
			$(this).find('td').removeClass('hover');
		});
	
	});

</script>
</head>
<body>
<table>
	<thead>
		<tr>
			<th>번호</th><th>이름</th><th>주소</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>111</td><td>아이유1</td><td>서초동</td>
		</tr>
		<tr>
			<td>222</td><td>아이유2</td><td>서초동</td>
		</tr>
		<tr>
			<td>333</td><td>아이유3</td><td>서초동</td>
		</tr>
		<tr>
			<td>444</td><td>아이유4</td><td>서초동</td>
		</tr>
	</tbody>

</table>
</body>
</html>

 

마우스를 올리면 색이 변함

 

 

 

  • traversal : parent, children, find 함수 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	table tr td{border: 2px solid black; margin:10px; width:80px; height:90;}
	.small>img{border:none; margin:10px; width:80px; height:90px;} /* small>img 직계자식*/
	.large>img{width:450px;} 
	.hover{background: Lavender; color:black; font-weight: bold;}
	.css{font-size:12px; font-weight:bold; color:tomato;} 
	
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		// 1. 마우스가 작은 이미지 영역 안으로 들어가면 hover이벤트 발생하도록 선택자와 함수를 연결
			$('.small').hover(function(){
				// == mouseenter 
				$(this).parent().addClass('hover'); //td 태그를 선택한 결과이다.
				var imagename = $(this).attr('href'); // attr :: 속성변경
				//alert(imagename);
				
				//fadeOut, In :: 슬라이딩 효과
				$('.large').children().fadeOut(2000);
				$('.large').children().attr('src',imagename);
				$('.large').children().fadeIn(3000);
				
			}, function(){
				// == mouseleave
				$(this).parent().removeClass('hover');
				
				
			}); // === hover
			
			
			
		// 2. td태그 중에서 (자손중에서) p태그를 찾아서(발견되면) css를 addClass 시키세요
			$('td').find('p').addClass('css');
		});
</script>
</head>
<body>
<table>
	<tr>
		<td align="center" width="150" height="200">
			<a href="../image/2.jpg" class="small">
				<img alt="" src="../image/2.jpg">
			</a>
			<p>이무진</p>
		</td>
		<!-- 첫번째 tr에 두번째 td , rowspan="5" :: 가운데로옴-->
		<td width="350" align = "center" rowspan="5">
			<a href="../image/2.jpg" class="large">
				<img alt="" src="../image/2.jpg">
			</a>
		</td>
	</tr>
	
	<tr>
		<td align="center" width="150" height="200">
			<a href="../image/3.jpg" class="small">
				<img alt="" src="../image/3.jpg">
			</a>
			<p>정홍일</p>
		</td>
	</tr>
	<tr>
		<td align="center" width="150" height="200">
			<a href="../image/4.jpg" class="small">
				<img alt="" src="../image/4.jpg">
			</a>
			<p>아이유</p>
		</td>
	</tr>
	<tr>
		<td align="center" width="150" height="200">
			<a href="../image/5.jpg" class="small">
				<img alt="" src="../image/5.jpg">
			</a>
			<p>이효리</p>
		</td>
	</tr>
		<tr>
		<td align="center" width="150" height="200">
			<a href="../image/1.jpg" class="small">
				<img alt="" src="../image/1.jpg">
			</a>
			<p>이승윤</p>
		</td>
	</tr>
</table>
</body>
</html>

 

 

 

 

 

  • click prevent : button 을 클릭하면 event 가 발생한다

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		// 1. 첫번째 h2태그를 클릭하면 , 이벤트 적용된 태그데 CLICK 이라는 메세지를 출력 (글자색은 red)
/* 		$('h2:eq(0)').click(function(){
			$(this).html('<font color=red>CLICK</font>');
			//$(this).text('<font color=red>CLICK</font>'); // text :: ()안에 모든것을 text기반으로 변경 후 뿌린다
			alert('CLICK()....calling...!') */
			
		
			
/* 		$('h2:eq(0)').bind('click',function(){
			$(this).html('<font color=red>CLICK</font>');
			alert('CLICK()....calling...!'); */
		
			
 		$('h2:eq(0)').on('click',function(){
			$(this).html('<font color=red>CLICK</font>');
			alert('CLICK()....calling...!');	 
			
		// 클릭 이벤트가 더 이상 작동되지 않도록 한다 -> bind 해제한다.
			$(this).unbind();
			
			
		// **** 한번만 호출 
		
/* 		$('h2:eq(0)').one('click',function(){ // 한번만 호출
			$(this).html('<font color=red>CLICK</font>');
			alert('CLICK()....calling...!')  */
		});
	});
</script>
</head>
<body>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library.</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library.</h2>
	<h2>jQuery is a fast, small, and feature-rich JavaScript library.</h2>
</body>
</html>

 

 

 

 

  • key event 

 

1. javascript

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> javascript :: keyevent</title>
<style type="text/css">

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	function input(){ //선언적 함수
		var value = document.frm.id.value;
		alert(value);
	}
</script>
</head>
<body>
<form name="frm">
	<!-- textbox 안에 text를 입력하고 enter 치면 event 발생하는 것도 click 이벤트이다 -->
	
	키 이벤트 - 아이디 입력 : <input type ="text" name = "id" id ="id" onkeyup = "input()"> 
</form>
</body>
</html>

 

 

 

2. jQuery

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery :: keyevent</title>
<style type="text/css">

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		// 선택적 함수
		$('#id').keyup(function () {
			alert($('#id').val());
		})
	});
</script>
</head>
<body>
<form name="frm">
	키 이벤트 - 아이디 입력 : <input type ="text" name = "id" id ="id">
</form>
</body>
</html>

 

 

 

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 방명록 </title>
<style type="text/css">

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
		//1. 
		$('textarea').keyup(function () {
			// 지금까지 입력한 글자의 개수를 받아온다.
			var inputlength = $(this).val().length;
			//alert(inputlength);
		 
		
		//2. h1영역에 10/70 이런 방식으로 출력하자 :: html() 사용
			var remain = 70-inputlength+1;
			$('h1').html(remain+'/70');
			
		// 3. remain 값에 따라서 h1 부분의 글자색깔이 달라지도록
			if(remain<=0)
				alert("글자 입력 안됨!");
			else if(remain<=10)
				$('h1').css('color','red');
			else if(remain<=20)
				$('h1').css('color','hotpink');
			else if(remain<=40)
				$('h1').css('color','purple');
			else
				$('h1').css('color','gray');
		
		
		});
	}); //keyup
</script>
</head>
<body>
	<div> <!-- strong :: 굵은글씨 -->
		<p><strong>방명록 입니다. 70자 이내로 짧은 소견들 남겨 주세요</strong></p>
		<h1>70</h1>
		<textarea rows="5" cols="70" maxlength="70"></textarea> 
		<!-- rows="5" (세로, 5줄) cols="70" (가로, 70자) -->
	</div>
</body>
</html>

 

 

 

 

  • select

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	$(function(){
	//1. 버튼 클릭시 함수 호출 (Test)
		
		$('#createBtn').click(function(){
		// --- 버튼의 함수를 한번만 출력
			//$('#resultView').html($(this).val()); // 버튼의 함수를 한번만 출력
						
		// --- 버튼의 함수를 연속적 출력
			//$('#resultView').append($(this).val()+"<p></p>"); 
			
		// --- html() 을 이용해서 append와 동일한 결과를 출력
			var result = $('#resultView').html(); //처음엔 내용이 없음
			$('#resultView').html(result+$(this).val()+"<p></p>")
			
		}); //click
		
		
		
		
		
	//2. select 폼에서 내가 선택한 영화가 resultView 영역에 뿌려지도록(동적으로)
		
/* 		$('#createSel').change(function () {
			var result=$('#resultView').html();
			var item = $('#createSel>option:selected').val()
			$('#resultView').html(result+item+"<p></p>")
		}); */
		
		
		$('#createSel').change(function () {
			var result = $('#resultView').html();
			$('#resultView').html(result+$(this).val()+"<p></p>")
		}); //change
	});
</script>
</head>
<body>
	<h2>9월 상영 영화</h2>
	<input type="button" value="버튼클릭시 동적으로 문자열 생성하기" id="createBtn">
	<select id="createSel">
		<option>샹치와 텐 링즈의 전설</option>
		<option>최선의 삶</option>
		<option>인질</option>
		<option>건파우더 밀크셰이크</option>
		<option>코다</option>
	</select>
	<div id="resultView"></div>
	
</body>
</html>

 

댓글