웹프로그래밍/jQuery

[jQuery] 메서드

아잠만_ 2024. 5. 20. 17:35

내용 확인 및 변경 메서드

메서드 설 명
html() 일치된 요소의 html내용을 가져온다 . innerHTML 기능과 동일하다 .
일치된 요소가 여러 개 라면 그 중 첫번째 요소의 html내용만 가져온다
html(code) 일치된 요소의 본문을 html내용으로 변경한다
일치된 요소가 여러 개 라면 모든 요소에 적용된다
text() 일치된 모드 요소를 내용을 가져온다
내용 중에 Html코드가 있다면 html코드는 제외한다
text(str)  일치된 모든 요소의 내용을 str로 변경한다
val() 해당 입력 요소의 value 속성값을 가져온다
val(data) 해당 입력 요소의 value 속성값을 data로 변경한다

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>

$(function(){
	$('#btnview').on('click',function(){
		// 입력한 모든 정보를 가져온다 - val()
		let str="";
		str+=`이름 : ${$('#user').val()} <br>
			성별 : ${$('.gend:checked').val()}<br><br>
			<소개> <br> ${$('#intro').val().replace(/\n/g,"<br>")}<br><br>
			직업 : ${$('#work option:selected').text()}`;
			
		$('#result').html(str);
	})
	
	
	$('#btnchange').on('click',function(){
		let name = prompt("이름을 입력하세요");
		$('#user').val(name);
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<div id="result1">
			<form>
				<label for="user">이름</label> 
				<input type="text" id="user" value="korea"><br> 
				<label>성별</label> 
				<input type="radio" id="gend " class="gend" name="gend" value="남자" checked>남자
				<input type="radio" id="gend " class="gend" name="gend" value="여자">여자<br>
				<label for="intro">소개</label>
				<textarea id="intro" cols="40" rows="4"></textarea>
				<br> <label for="work">직업</label> 
				<select id="work">
					<option value="programmer">프로그래머</option>
					<option value="progammer">프로게이머</option>
					<option value="whitehand">백수</option>
				</select><br>
				<button id="btnview" type="button">조사하기</button>		<!-- submit -->
				<!-- prompt로 이름을 입력받아 user요소에 출력-->
				<button type="button" id="btnchange">이름변경</button>
			</form>
		</div>
		
		<div id="result"></div>
	</div>
</body>
</html>

선택요소내부에 추가하는 메서드

메서드 설 명
append(content) 일치된요소 내부의마지막 위치에content를 추가한다
appendTo(selector) 선택된 요소를 selector에 일치된 모든 요소들의 내부
마지막 위치에추가한다.
만일, 일치된요소가 본문에 존재하면그 요소를 제거한
후 복사한다. (즉, 이동)
prepend(content) append(content)와 동일,
다만, 내부의처음위치에추가한다.
prependTo(selector) appendTo(selector)와 동일,
다만, 내부의처음위치에추가한다.
after(content) 일치된요소 뒤에content를 삽입한다.
요소 내부가 아닌 외부에삽입된다.
insertAfter(selector) 선택된요소를 selector에 의해일치된모든 요소들
뒤쪽에삽입한다. 요소 내부가 아닌 외부에삽입된다.
before(content) 일치된요소 앞에 content를 삽입한다.
요소 내부가 아닌 외부에삽입된다.
insertBefore(selector) insertAfter(selector)와 유사하나, 요소 앞 쪽에
삽입한다. 요소 내부가 아닌 외부에삽입된다.

append() / prepend() 예제

 

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
	const arr = [ "image.1.jpg", "image.2.jpg", "image.3.jpg", "image.4.jpg",
			"image.5.jpg", "image.6.jpg", "image.7.jpg" ]

	$(function() {
		$('#btn1').on('click', function() {

			ran = parseInt(Math.random() * arr.length);

			// 이미지 객체 (요소) 생성
			vimg = $('<img>', {
				"src" : `../images/${arr[ran]}`,
				"alt" : arr[ran]
			})

			// vimg.appendTo($('#result1'));
			$('#result1').append(vimg);
		})
		
		$('#btn2').on('click', function() {
			ran = parseInt(Math.random() * arr.length);

			// 이미지 객체 (요소) 생성
			vimg = $('<img>', {
				"src" : `../images/${arr[ran]}`,
				"alt" : arr[ran]
			})

			// vimg.prependTo($('#result1'));
			$('#result2').prepend(vimg);

		})
	})
</script>
</head>
<body>

	<div class="box">
		<h3>새로운 이미지를 추가한다</h3>
		<input type="button" value="append" id="btn1"> 
		<input type="button" value="prepend" id="btn2">
		<br> <br>

		<div id="result1">
			<p>이미지 추가하기 - 뒤로 - append</p>
		</div>
		<div id="result2">
			<p>이미지 추가하기 - 앞으로 - prepend</p>
		</div>
	</div>
</body>
</html>

before() / after() 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
const arr = [ "image.1.jpg", "image.2.jpg", "image.3.jpg", "image.4.jpg",
	"image.5.jpg", "image.6.jpg", "image.7.jpg" ]
	
$(function() {
	$('#btn1').on('click', function() {
		ran = parseInt(Math.random() * arr.length);
		
		// 이미지 객체 (요소) 생성
		vimg = $('<img>', {
			"src" : `../images/${arr[ran]}`,
			"alt" : arr[ran]
		})
		
// 		vimg.insertAfter($('#result1'));
		$('#result1').after(vimg);
	})
	
	$('#btn2').on('click', function() {
		ran = parseInt(Math.random() * arr.length);
		
		// 이미지 객체 (요소) 생성
		vimg = $('<img>', {
			"src" : `../images/${arr[ran]}`,
			"alt" : arr[ran]
		})
		
// 		vimg.insertBefore($('#result2'));
		$('#result2').before(vimg);
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="after" id="btn1"> 
		<input type="button" value="before" id="btn2"> <br> <br>

		<div id="result1">
			<p>이미지 추가하기 - 요소 뒤 - after</p>
		</div>
		<hr>
		<div id="result2">
			<p>이미지 추가하기 - 요소 앞 - before</p>
		</div>
	</div>
</body>
</html>

삭제 메서드

메서드 설 명
empty() 선택된 모든요소의 자식요소를 지운다
remove
remove(selector)
선택된 모든 요소와 그의 자식요소를 지운다
$(‘p’).remove(‘.test’)

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	$('#btn1').click(function(){
		
	})
	$('#btn1').on('click',function(){
		$('#result1').empty();
	})
	$('#btn2').on('click',function(){
		$('#result2').remove();
	})
	$('#btn3').on('click',function(){
		$('#result1 p').remove();
	})
	$('#btn4').on('click',function(){
		$('#result1 p').remove('#p1');
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3>empty : result1의 내용을 지우기<br>
		remove : result2을 지우기<br>
		p_remove : result1의 모든 p태그를 지우기<br>
		p_remove_id : result1의 p태그를 지우기</h3>
		<input type="button" value="empty" id="btn1"> 
		<input type="button" value="remove" id="btn2">
		<input type="button" value="p_remove" id="btn3"> 
		<input type="button" value="p_remove_id" id="btn4"> <br> <br>

		<div id="result1">
			<p id="p1">무궁화꽃이 피었습니다1</p>
			<p id="p2">무궁화꽃이 피었습니다2</p>
			<p id="p3">무궁화꽃이 피었습니다3</p>
		</div>
		<hr>
		<div id="result2">
			<p>무궁화꽃이 피었습니다1</p>
			<p>무궁화꽃이 피었습니다2</p>
			<p>무궁화꽃이 피었습니다3</p>
		</div>
	</div>
</body>
</html>

복사 메서드

메서드 설 명
clone() 일치된 요소를 복사하고 선택한다
clone(true) 일치된 요소의 이벤트 처리기를 포함하여 복사하고 선택한 다

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	// p태그의 이벤트 - 글자크기 확대
	$('p').on('click',function(){
		$(this).css("font-size","+=3px");
	})
	
	$('#btn1').on('click',function(){
		let vp1 = $('#p1').clone();
		$('#result2').append(vp1);
	})
	
})
</script>
</head>
<body>

	<div class="box">
		<h3>p태그에 대한 이벤트 설정<br>
		result1의 p태그를 result2으로 복사<br>
		clone(true) 적용시 이벤트를 포함해서 복사한다</h3>
		<input type="button" value="clone" id="btn1"> <br> <br>
		<input type="button" value="clone(true)" id="btn2"> <br> <br>

		<div id="result1">
			<p id="p1">무궁화 꽃이 피었습니다1</p>
			<p id="p2">무궁화 꽃이 피었습니다2</p>
		</div>
		
		<div id="result2">

		</div>
	</div>
</body>
</html>

필터링 메서드

메서드 설 명
eq(index) 선택요소중 index번째의 요소
first() 선택요소 중 가장 첫 번째 요소
last() 선택요소 중 가장 마지막 번째 요소
even() 선택요소 중 짝수번째
odd() 선택요소 중 홀수번째
filter(selector)  선택요소 중 Selector와 일치하는 요소를 필터링한다
filter (‘:gt(1)’) filter(‘:even’) filter(‘:first)’
is(selectorElement) 선택요소가 selectorElement 와 일치하는지 판단
true/ false를 리턴

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	$('#btn1').on('click', function(){
// 		$('p:first').css('color','red')
// 		$('p').first().css('color','red')
		$('p').filter(':first').css('color','red')
		
// 		$('p:even').css('background','silver');
// 		$('p').even().css('background','silver');
		$('p').filter(':even').css('background','silver');
		
	})
})
</script>
</head>field
<body>

	<div class="box">
		<h3>
		p.first() / p:first<br>
		p.last() / p:last<br>
		p.even() / p:even</h3>
		<input type="button" value="확인" id="btn1"> <br> <br>

		<div id="result1">
			<p>무궁화 꽃이 피었습니다1</p>
			<p>무궁화 꽃이 피었습니다2</p>
			<p>무궁화 꽃이 피었습니다3</p>
			<p>무궁화 꽃이 피었습니다4</p>
			<p>무궁화 꽃이 피었습니다5</p>
			<p>무궁화 꽃이 피었습니다6</p>
			<p>무궁화 꽃이 피었습니다7</p>
			<p>무궁화 꽃이 피었습니다8</p>
		</div>
	</div>
</body>
</html>

찾기 탐색 메서드

메서드 설  명
add() 선택확장
next() nextAll()
nextUntil(selector)
선택요소의 다음 형제요소들
prev() prevAll()
prevUntil(selector)
선택요소의 이전 형제요소들
parent() parents()
parents(selector)
parentsUntil(selector)
선택요소의 부모요소
siblings()
siblings(selector)
선택요소의 앞뒤 모든 요소들
find() 선택요소의 후손요소들

next() 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.siblings * {
	display: block;
	border: 2px solid lightgrey;
	color: lightgrey;
	padding: 5px;
	margin: 15px;
}
.start{
	color : black;
}
</style>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
	$(document).ready(function() {
		
		$('#next').on('click', function(){
			$("#result1 li.start").next().css({
			"color" : "red",
			"border" : "2px solid red"
			});
		})
		$('#nextAll').on('click', function(){
			$("#result1 li.start").nextAll().css({
			"color" : "blue",
			"border" : "2px solid blue"
			});
		})
		$('#nextUntil').on('click', function(){
			$("#result1 li.start").nextUntil('#result1 li:last').css({
			"color" : "green",
			"border" : "2px solid green"
			});
		})
	});
</script>
</head>
<body>
	<div class="box">
		<h3></h3>
		<input type="button" value="next" id="next">
		<input type="button" value="nextAll" id="nextAll"> 
		<input type="button" value="nextUntil" id="nextUntil"> <br>
		<br>

		<div id="result1">
			<div style="width: 500px;" class="siblings">
				<ul>
					ul (parent)
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li class="start">li (sibling with class name "start")</li>
					<li>li (the next sibling of li with class name "start")</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
				</ul>
			</div>
		</div>
	</div>
</body>
</html>

prve() 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.siblings * {
	display: block;
	border: 2px solid lightgrey;
	color: lightgrey;
	padding: 5px;
	margin: 15px;
}
.start{
	color : black;
}
</style>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
	$(document).ready(function() {
		$('#prev').on('click', function(){
			$("#result2 li.start").prev().css({
			"color" : "red",
			"border" : "2px solid red"
			});
		})
		$('#prevAll').on('click', function(){
			$("#result2 li.start").prevAll().css({
			"color" : "blue",
			"border" : "2px solid blue"
			});
		})
		$('#prevUntil').on('click', function(){
			$("#result2 li.start").prevUntil('#result2 li:first').css({
			"color" : "green",
			"border" : "2px solid green"
			});
		})
	});
</script>
</head>
<body>
	<div class="box">
		<h3></h3>
		<input type="button" value="prev" id="prev">
		<input type="button" value="prevAll" id="prevAll"> 
		<input type="button" value="prevUntil" id="prevUntil"> <br>
		<br>

		<div id="result2">
			<div style="width: 500px;" class="siblings">
				<ul>
					ul (parent)
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li>li (sibling)</li>
					<li class="start">li (sibling with class name "start")</li>
					<li>li (the next sibling of li with class name "start")</li>
					<li>li (sibling)</li>
				</ul>
			</div>
		</div>
	</div>
</body>
</html>

parent() / find() 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.ancestors * {
	display: block;
	border: 2px solid lightgrey;
	color: lightgrey;
	padding: 5px;
	margin: 15px;
}
</style>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$('#parent').on('click',function(){
		$("#result1 span").parent().css({"color": "red", "border": "2px solid red"});
	})
	$('#parents').on('click',function(){
		$("#result1 span").parents().css({"color": "blue", "border": "2px solid blue"});
	})
	$('#parents_se').on('click',function(){
		$("#result1 span").parents('ul').css({"color": "green", "border": "2px solid green"});
	})
	$('#parents_un').on('click',function(){
		$("#result1 span").parentsUntil('#result1').css({"color": "orange", "border": "2px solid orange"});
	})
	// button[type=button]
	$('button:button').on('click',function(){
		
// 		let vul = $(this).parents('ul');
// 		$('span', vul).css({"color": "pink", "border": "2px solid pink"});
		$(this).parents('ul').find('span').css({"color": "pink", "border": "2px solid pink"});
	})
});
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="parent" id="parent">
		<input type="button" value="parents" id="parents"> 
		<input type="button" value="parents_se" id="parents_se"> 
		<input type="button" value="parents_un" id="parents_un"> <br> <br>

		<div id="result1" class="ancestors">
			<div style="width: 500px;">
				div (great-grandparent)
				<ul>
					ul (grandparent)
					<li>li (direct parent) <span>span</span>
					</li>
					<button type="button">확인</button>
				</ul>
			</div>
		</div>
		
		<div id="result2" class="ancestors">
			<div style="width: 500px;">
				div (great-grandparent)
				<ul>
					ul (grandparent)
					<li>li (direct parent) <span>span</span>
					</li>
					<button type="button">확인</button>
				</ul>
			</div>
		</div>
		
		<div id="result3" class="ancestors">
			<div style="width: 500px;">
				div (great-grandparent)
				<ul>
					ul (grandparent)
					<li>li (direct parent) <span>span</span>
					</li>
					<button type="button">확인</button>
				</ul>
			</div>
		</div>
	</div>
</body>
</html>

is() / parent() 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	$('p').on('click',function(){
		let vp = $(this).parent();
		if(vp.is('.dd')){
			let vp2 = $(this).clone().css("color","red");
// 			vp2.appendTo(vp).css("color","red");
			$(this).after(vp2);
		}else{
			alert("작업대상이 아닙니다");
		}
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3>a.is(b) : a가 b 일치 판단 true/ false 리턴<br>
		p태그를 클릭하면 부모가 .dd인지 비교</h3>

		<div id="result1" class="dd">
			<p>무궁화 꽃이 피었습니다</p>
		</div>
		
		<p>수업이 곧 끝난당</p>
		
		<div id="result2" class="dd">
			<p>시험 얼마 안남았다</p>
		</div>
		
	</div>
</body>
</html>

CSS 관련 메서드

메서드 설  명
css(name) 매치되는 첫번째 요소의 스타일의 속성을 반환한다
예) $(this).css(‘color’)
css(name, value) 매치되는 모든 요소들의 단일 스타일 속성을 설정한다
예) $(this).css(‘color’ , ‘red’)
css(propertis) 매치되는 모든 요소들의 스타일 속성에 키:값 을
설정한다
예) $(this.).css({‘color’:’blue’, ‘font-size’:’20px’ })

클래스 관련 메서드

메서드 설  명
addClass(class) 매치된 요소들의 집합에 지정된 css 클래스를 추가한다
hasClass(class) 지정된 클래스가 매치된 요소들의 집합 중 최소 한군데
이상 적용 되어 있으면 true 를 리턴 한다
removeClass(class) 매치된 요소들의 집합에서 지정된 css클래스를 삭제한다
toggleClass(class) 매치된 요소들에 지정된 클래스가 적용되지 않았다면
적용하고 , 이미 적용되어 있다면 제거한다

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	$('#btn1').on('click', function(){
		$('#result1').toggleClass('backc');
	})
	
	$('p').on('mouseover', function(){
		$(this).toggleClass('pback');
	})
	
	$('p').on('mouseout', function(){
		$(this).removeClass('pback');
	})
})
</script>
<style>
<!-- 외부스타일에서 이미 스타일이 적용 중인 경우 해당 스타일이 적용된 태그 이름이 같은 것만 다시 스타일이 적용된다 -->
.backc{
	background : skyblue;
}
.pback{
	background : pink;
}
.res{
	background : orange;
}
</style>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="확인" id="btn1"> <br> <br>

		<div id="result" class="res"></div>
		
		<div id="result1"></div>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
		<p>무궁화 꽃이 피었습니다</p>
	</div>
</body>
</html>

속성 메서드

메서드 설  명
attr(name) 매치된 첫번째 요소의 name에 지정된 속성의 값을 가
져온다. 지정된 속성 명이 존재하지 않는다면 undefined
가 반환된다
attr(properties) 매치되는 모든 요소들의 속성을 키:값 의 형태로 지정한다
attr(key, value) 매치되는 모든 요소들의 속성을 단일 값으로 지정한다
attr(key, fn) 매치되는 모든 요소들의 단일속성에 대한 fn에서 수행된
값을 지정한다
removeAttr(name) 매치된 요소의 속성을 제거한다

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<style>
img{
	width: 100px;
	height: 100px;
}
</style>
<script>
$(function() {
	$('#btn1').on('click',function(){
		// 전체 이미지를 대상으로 같은 값을 title속성 값을 설정
// 		$('img').attr('title', '이미지');
		
		$('img').attr('title', function(){
			// src 속성값 가져오기
			let vsrc = $(this).attr('src');
// 			vsrc = vtit.slice(10,vtit.length-4);

			// 2번째 /와 마지막 .의 위치를 알아내기
			let start = vsrc.lastIndexOf("/")+1;
			let end = vsrc.lastIndexOf(".");
			
			let vtitle = vsrc.slice(start, end);

			return vtitle;
		});
		
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3>img의 src의 이름을 추출하여 title속성으로 추가하기</h3>
		<input type="button" value="확인" id="btn1"> 
		<br> <br>

		<div id="result1">
		<img src="../images/국화1.jpg" alt="국화1">
		<img src="../images/국화2.jpg" alt="국화2">
		<img src="../images/국화3.jpg" alt="국화3">
		<img src="../images/국화4.jpg" alt="국화4">
		<img src="../images/국화5.jpg" alt="국화5">
		<img src="../images/국화6.jpg" alt="국화6">
		</div>
	</div>
</body>
</html>

prop("속성명", 상태) - set  |  prop("속성명") - get

  • 속성 상태 설정 및 상태 얻는 메서드
  • element가 가지는 실제적인 상태(활성화, 체크 선택여부)등을 제어
             (예: checked, selected, disabled, readonly, multiple )
  • 가져올때(get) true 또는 false 를 리턴하고 /설정(set)시 true 또는 false 로 설정한다

예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
$(function(){
	$('#btn1').on('click',function(){
		// 현재의 상태값을 가져온다
		let vchk = $('#checkTest').prop('checked');
		let vread = $('#txtTest').prop('readonly');
		let vbtn = $('#runBtn').prop('disabled');
		let vsel = false;

		let num = 0;
		while(true){
			vsel = $('#selTest option').eq(num).prop('selected');
			if(vsel){
				$('#selTest option').eq(num).prop('selected',false);
				$('#selTest option').eq(num).next().prop('selected',true);
				break;
			}
			num++;
		}
		
		$('#checkTest').prop('checked',!vchk);
		$('#txtTest').prop('readonly',!vread);
		$('#runBtn').prop('disabled',!vbtn);
	})
	
	$('#check').on('change',function(){
		let vchk = $(this).prop('checked');
		$('.chk').prop('checked',vchk);
	})
})	
</script>
</head>
<body>

	<div class="box">
		<h3>실행버튼 클릭할때마다 각 상태값을 선택과 해제(true/false)로<br>
			번갈아가면서 변경</h3>
		<input type="button" value="실행" id="btn1"> <br> <br>

		<div id="result1">
			<form>
				체크박스(라디오버튼) : <input type="checkbox" id="checkTest" checked>
				<br><br> 리스트박스(select객체) :
				
				<select id="selTest">
					<option value="1">하나</option>
					<option value="2">둘</option>
					<option value="3" selected >셋</option>
					<option value="4">넷</option>
				</select><br>
				<br> text객체 (readonly) : <input type="text" value="가나다" id="txtTest"><br>
				<br> button객체(disabled) : <input type="button" value="실행" id="runBtn" onclick="alert('Hello')">
			</form>
		</div>
	</div>
	
	<div class="box">
		<h3>전체선택의 상태 값으로 1~5 의 상태값을 설정</h3>
		<div id="result2">
			<form>
				체크박스(전체선택/해제) : <br>
				<input type="checkbox" id="check"> 전체선택
				<input type="checkbox" class="chk">1
				<input type="checkbox" class="chk">2
				<input type="checkbox" class="chk">3
				<input type="checkbox" class="chk">4
				<input type="checkbox" class="chk">5
			</form>
		</div>
	</div>
</body>
</html>

이벤트관련 메서드

더보기
더보기
더보기
// 실행 전에 이미 body태그 안에 만들어져 있는 요소
$('btn1').on('click', function(){ })
$('btn1').bind('click', function(){ })
$('btn1').click(function(){ })

// 실행 후에 생성 (& 기존에 존재하는) 새로운 요소(id='ss')에 대한 이벤트 핸들러
$(document).delegate('#ss', 'click', function(){ })
$(document).on('click', '#ss', function(){ })
  • version 3.0에서 모든 이벤트 등록 메서드를 통합하는 메서드가 도입
    • on(이벤트명, [선택자], 핸들러)
      선택자가 있다면 delegate와 같고 없다면 bind와 같다
    • off(이벤트명, [선택자], 핸들러) 
      선택자가 있다면 undelegate와 같고 없다면 unbind와 같다
메서드 설  명
bind(type, data, fn, map)

on(type, data, fn, map)
매치돤 요소에 이벤트처리기를 바인딩한다
type : 이벤트종류, data: fn의 파라미터값,
Version3.0 deprecated ,Use the on() method
map: {event:function(){}, event:function(){}, ...}
unbind(type, fn)

off(type, fn)
매치돤 요소에 이벤트 처리기를 제거한다
Version3.0 deprecated
Use the off() method instead
one(type, data, fn) bind()와 같지만 이벤트를 한번만 실행하고 자동으로 이벤트를 제거한다
----map 표현----
$("p").on({
mouseover: function(){ $(this).css("background-color", "lightgray"); },
mouseout: function(){ $(this).css("background-color", "lightblue"); },
click: function() { $(this).css("background-color", "yellow"); }
});
메서드 설  명
delegate(selector, type, data, fn)

on(type, selector, data, fn)
매치돤 요소에 이벤트처리기를 바인딩한다
동적으로 작성된 새로운 요소에서도이벤트실행
type : 이벤트종류, data:fn의 파라미터값,
Version3.0 deprecated
Use the on() method instead
undegate(selector, type, data, fn)

off(type, selector, data, fn)
매치돤 요소에 이벤트 처리기를 제거한다
Version3.0 deprecated
Use the off() method instead
trigger(type) 매치된 요소에 대하여 이벤트 타입에 해당하는 이벤트 처
리기를 모두 실행한다 type에 사용자 정의 이벤트 가 올 수 있다
$("button").click(function(){
$(this).background(“blue”)
$("p").trigger(“click”]);
});
$("p").on(“click", function(){
$(this).text(“hello~~~”);
});
메서드 설  명
on(type, data, fn, map ) 매치돤 요소에 이벤트처리기를 바인딩한다
bind방식
on(type, selector, data, fn, map ) delegate 방식 동적으로작성된새로운요소
off(event, selector) 매치돤요소에에 이벤트처리기를 제거한다
----map 표현----
$("p").on({
mouseover: function(){ $(this).css("background-color", "lightgray"); },
mouseout: function(){ $(this).css("background-color", "lightblue"); },
click: function() { $(this).css("background-color", "yellow"); }
});

delegate() 예제 

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
let num = 1;
$(function(){
	
	$('#add').on('click',function(){
		let vbtn = $('<input>',{
			"class" : "add",
			"type" : "button",
			"value" : `새로운버튼${num++}`
		})
		
		$('#result1').append(vbtn);
	});
	
	$(document).on('click','.add', function(){
		let vr = parseInt(Math.random()*256);
		let vg = parseInt(Math.random()*256);
		let vb = parseInt(Math.random()*256);
		
		$('#result2').css('background', `rgb(${vr},${vg},${vb})`);
	})
	// 해제 버튼 이벤트 핸들러
	$('#stop').on('click', function(){
		$('#add').off('click');
	});
	
})

</script>
</head>
<body>

	<div class="box">
		<h3>새롭게 추가된 새로운 버튼은 이벤트 핸들러가 실행되지 않는다</h3>
		<input type="button" value="추가" id="add">
		<input type="button" value="해제" id="stop">
		 <br> <br>
		<div id="result1"></div>
		<div id="result2"></div>
	</div>
</body>
</html>

delegate() 예제2

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<style>
label{
	display : inline-block;
	width : 50px;
}
</style>
<script>
$(function(){
	$('#add').on('click',function(){
// 		vlabel = $('<label>',{
// 			"text" : "파일"
// 		});
// 		vfile = $('<input>',{
// 			"type" : "file"
// 		});
// 		vbtn = $('<input type="button" value="삭제" class="remove">');
// 		vp = $('<span>')
		
// 		$(vp).append(vlabel);
// 		$(vp).append(vfile);
// 		$(vp).append(vbtn);
// 		$(vp).append('<br>');
		
		vp = $('<p><input type="file"> <input type="button" value="삭제" class="remove"></p>');
		
		$('#result1').append(vp);
	})
	
	$(document).on('click','.remove',function(){
		$(this).parent().remove();
	})
})
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		<div id="result1">
			<label>이름</label> 
			<input>
			<br>
			<label>파일</label>
			<input type="file"> <input type="button" value="추가" id="add"> <br>
		</div>
	</div>
</body>
</html>