웹프로그래밍/jQuery

[jQuery] js와 차이

아잠만_ 2024. 5. 16. 15:36

JavaScript와 Jquery 코드 차이

java script jquery
document.querySelector(' ') $(' ')
window.onload = function() { } $(document).ready(function(){ })
$(function(){ })
innerHTML html()
innerText text()
style.backgroudColor=' '; css('background-color', ' ')
this 객체(dom객체) $(this) > jquery변수로 변환
addEventListener(' ',function(){ }) on(' ', function(){ })
let vh1 = document.getElementsByTagName('h1');
for(i=0; i<vh1.length; i++){
   vh1[i].style.backgroundColor="gray";
}
let vh1 = $('h1');
vh1.css('background-color', 'gray');

(전체 태그의 스타일을 반복문 없이 한번에 설정)

<!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 src="../js/jquery-3.7.1.js"></script> -->
<script>
$(document).ready(() => {
	// js 방식
// 	let vh1 = document.getElementsByTagName('h1');
// 	for(i=0; i<vh1.length; i++){
// 		vh1[i].style.backgroundColor="gray";
// 		vh1[i].addEventListener('click',function(){
// 			this.style.color="white";
// 		})
// 	}

	// jquery
	let vh1 = $('h1');
	vh1.css('background-color', 'gray');
	vh1.eq(2).css('background-color', 'black');
	vh1.on('click',function(){
		$(this).css('color','white');
	})
})

</script>
</head>
<body>

	<div class="box">
		<h3>h1태그를 클릭했을 때 이벤트 핸들러 작성</h3>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<h1>무궁화 꽃이 피었습니다</h1>
		<div id="result1"></div>
	</div>
</body>
</html>

클릭하면 사라지는 예제 ( hide(), show() )

style.display = "none"
css('display', 'none')
hide() <-> show()

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
input{
	display : none;
}
</style>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
	$(document).ready(function(){
		let vh = $('h2');
		vh.on('click',function(){
// 			$(this).css("display","none");
			$(this).hide();
			
			// 다 사라졌는지 비교 - 보이는 개수가 0개인지 확인
			if($('h2:visible').length < 1){	// : 비교 붙혀서 쓰기 :visible보이는 h2 (필터)
// 				$('input').css('display','inline');
				$('input').show();
			}
		})
	})
	
	const proc1 = () =>{
		let vh = $('h2');
		vh.show();
		// vh.css('display','block');
		$('input').hide();
	}
</script>
</head>
<body>

	<div class="box">
		<h3>버튼을 생성해서 초기설정은 안보이도록 h2요소가 다 사라지면 button을 보이도록 설정
		button을 클릭하면 h2요소가 전부 다시 보여지도록 함</h3>
		<div id="result1">
		<h2>클릭하면 사라집니다1.</h2>
		<h2>클릭하면 사라집니다2.</h2>
		<h2>클릭하면 사라집니다3.</h2>
		<h2>클릭하면 사라집니다4.</h2>
		<h2>클릭하면 사라집니다5.</h2>
		<h2>클릭하면 사라집니다6.</h2>
		<h2>클릭하면 사라집니다7.</h2>
		</div>
		<input type="button" value="초기화" onclick="proc1()"> <br> <br>
	</div>
</body>
</html>



컨텍스트

$( 선택자 , [컨텍스트] )

검색범위를 지정해준다

$('p') : 문서 전체에서 p태그를 검색

$('p', documentforms[0]) :0번째 form객체 안에서만 p태그 검색

$(태그, 부모)


<!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(){
	// $(선택자, [컨텍스트])
// 	let vp = $('form:eq(1) p');
	let vp = $('p',document.forms[0]);	// form 태그 안에 있는 index 1번째의 p태그
	vp.css('color','red');
	
	// class = 'dd'를 클릭하면 그 자식 p태그를 검색
	$('.dd').on('click', function(){
		$('p', this).css('background','lightgray');
	})
})

</script>
</head>
<body>

	<div class="box">
		<h3>컨텍스트 : 검색 범위 지정
		div class=dd를 클릭하면 클릭한 곳 자식 p태그 검색</h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>
		<p> 무궁화 꽃이 피었습니다 </p>
		<div id="result1" class='dd'>
			<p>햇빛이 선명하게 나뭇잎을 핥고 있었다</p>
		</div>
		<div id="result2" class='dd'>
			<p>햇빛이 선명하게 나뭇잎을 핥고 있었다</p>
		</div>
		
		<form>
			<p>이웃집 토토로</p>
		</form>
		<form>
			<p>센과 치히로의 행방불명</p>
		</form>
	</div>
</body>
</html>

이미지 넣기

<!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"]

const proc1 = () => {
	let ran = parseInt(Math.random()*arr.length);
	
// 	let vimg = $(`<img src='../images/${arr[ran]}' onclick='procImg(this)'>`)
	let vimg = $('<img>', {
		"src" : "../images/"+arr[ran],
		"click" : imgBorder
	})
	
	// id=result1에 추가
	vimg.appendTo($('#result1'));
}
function procImg(target) {
	$(target).css("border","3px solid teal");
}
function imgBorder() {
	$(this).css("border","3px solid gray");
}
</script>
<style>
img {
	width: 100px;
	height: 100px;
}
</style>
</head>
<body>

	<div class="box">
		<h3></h3>
		<input type="button" value="이미지 만들기" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
</body>
</html>