본문 바로가기

UI/JavaScript

221025_JavaScript_JQUERY_국비_자바스크립트 객체 및 배열

<예시_1>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_1.html/ 포커스를 받으면 글씨 지우고 포커스를 잃으면 글씨 나타내기</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function() {
		$('input').val("아이디를 입력하세요").css('color', 'red');
		
		//동일의미 $('input').bind('focus', function(event) {
		$('input').focus(function(event) {
			$(event.target).val("").css("color", "#000");
			//input태그에 text를 입력 후 다시 포커스 이벤트를 받았을때 text를 지움
		});
		$('input').blur(function(event) {
			if ($(event.target).val() == "") {
				$(event.target).val("아이디를 입력하세요").css('color', 'red');
			}
		});
	});
	//focus(): 대상 엘리먼트가 포커스를 얻었을때 전달되는 이벤트 처리
	//blur() : 대상 엘리먼트가 포커스를 잃었을때 전달되는 이벤트 처리
</script>
</head>
<body>
	<input type="text" id="ID">
</body>
</html>

 

↓결과

포커스를 잃었을 때 / 포커스를 얻었을 때

 

 

<예시_2>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_2.html/콤보박스에서 선택한 과일 그림 출력</title>
<style>
	img{width:80px; height:80px; margin-left:50px;}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('#sel').change(function(event){
			var imgSrc = $(event.target).val();
			$('#img').attr('src',imgSrc);
		}).change();
	});

	//change():값이 변경될때 실행되는 이벤트 처리
</script>
</head>
<body>
<form name="frm">
	<table>
		<tr>
			<td>
				<select id="sel">
					<option value="../images/strawberry.jpg">딸기
					<option value="../images/banana.gif">바나나
					<option value="../images/apple.gif" selected>사과
				</select>
			</td>
			<td><img id="img"></td>
		</tr>
	</table>
</form>
</body>
</html>

 

↓결과

 

 

<예시_3>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_3.html/ 해당 엘리먼트를 보이게 하기</title>
<style>
	span{display:none}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('#kbs').click(function(){
			$('#mbc').show();
		});
		$('button:eq(1)').click(function(){
			$('span:eq(1)').show();
		});
		$('button:eq(2)').click(function(){
			$('span:eq(2)').show('slow',function(){
				$(this).css('background','yellow');
			});
		});
		$('button:eq(3)').click(function(){
			$('span:eq(3)').show('slow',function(){
				$(this).css('background','#dd5577aa');
			});
		});
	});
	//show():엘리먼트를 나타나게함
	//slow() : slow이외의 문자열은 400밀리초동안 애니메이션 진행
	//			0이상의 숫자(밀리 세컨드다위)를 줄 수 있음				
</script>
</head>
<body>
	<button id="kbs">show it</button>
	<span id="mbc">hello</span><br>
	<button>show it2</button>
	<span>hello2</span><br>
	<button>show it slow</button>
	<span>world</span><br>
	<button>show it slow2</button>
	<span>world2</span>
	

</body>
</html>

 

↓결과

 

 

<예시_4_1>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_4.html/해당 엘리먼트를 사라지게 하기</title>
<style>
	span{display:none}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('button:eq(0)').click(function(){
			$('span:first').show();
		});
		$('button:eq(2)').click(function(){
			$('span:last').show('slow',function(){
				$(this).css('background','yellow');
			});
		});
		$('button:eq(1)').click(function(){
			$('span:first').hide()
			});
		$('button:eq(3)').click(function(){
			$('span:last').hide('slow',function(){
				$(this).css('background','');
				});
			});
		});
		//hide():엘리먼트를 사라지게함
</script>
</head>
<body>
<button>show it</button><button>hide it</button>
<span>hello</span><br>
<button>show it slow</button><button>hide it slow</button>
<span>hello world</span>
</body>
</html>

 

↓결과

 

 

<예시_4_2>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_5.html/ 해당 엘리먼트 사라지게 하기</title>
<style>
	span{display:none}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('button:eq(0)').click(function(){
			$('span:first').toggle();
		});
		$('button:eq(1)').click(function(){
			$('span:last').toggle('slow',function(){
				$(this).css('background','yellow');
			});
		});
	});
	//toggle():엘리먼트가 사라졌다 나타나도록 하는 상태를 반복
</script>
</head>
<body>
<button>show & hide it</button>
<span>hello</span><br>
<button>show & hide it slow</button>
<span>hello</span>
</body>
</html>

 

↓결과

 

 

<예시_5>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jq5_6.html/ sliding</title>
<style>
	div{background:#3d9a44; margin:3px;
		width:80px; height:40px;
		float:left;}
	p{clear:left;}
	/* float의 left처리 취소 */
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('#slideup').click(function(){
			$('div').slideUp();
				});
			$('#slidedown').click(function(){
				$('div').slideDown('slow');
				});
			$('#slidetoggle').click(function(){
				$('div').slideToggle('fast');
				});
		});
		//slideUp():엘리먼트의 높이가 서서히 0에 가깝게 줄어가며 사라짐
		//slideToggle() : 해당 엘리먼트의 상테에 따라 위로 사라지게 하거나 내려서 등장
</script>
</head>
<body>
<button id="slideup">slideup</button>
<button id="slidedown">slidedown</button>
<button id="slidetoggle">slidetoggle</button>
<br>
<div></div><div></div><div></div>
<p>
<div></div><div></div><div></div>
</body>
</html>

 

↓결과

 

 

<예시_6>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>해당엘리먼트를 서서히 보이게 하기</title>
<style>
	span{color:red; cursor:pointer}
	div{margin:3px; width:80px;
		display:none; height:80px;
		float:left;}
	#red{background:red}
	#green{background:green}
	div#blue{background:#00f}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$(document.body).click(function(){
			$('div:hidden:first').fadeIn("slow");
		});
	});
	//fadeIn():엘리먼트의 불투명도를 점차 높여서 엘리먼트가 보이도록 함
	//hide:first 숨겨진 div 엘리먼트중 첫번째 div엘리먼트가 서서히 나타남
</script>
</head>
<body>
<span>클릭</span><p>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
</body>
</html>

 

↓결과

클릭할때 마다 div가 출력됨

 

 

<예시_7>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>페이딩</title>
<style>
	p{position:relation; width:400px; height:90px;}
	div{
		position:absolute; width:400px; height:65px;
		font-size:36px; text-align:center;
		color:yellow; background:red;
		padding-top:25px;
		top:0; left:0; display:none;
	}
	span{display:none}
</style>
<script type="text/javascript"src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('#fadein').click(function(){
			$('div').fadeIn(3000,function(){
				$('span').fadeIn(100);
			});
			return false;
		});
		//.fadeOut() : 선택한 요소를 서서히 사라지게 하고
		//.fadeIn() :  서서히 나타나게함
		//인수로 밀리초(ms)를 설정하거나 'slow','fast'와 같은 예약어 전달가능
		
		$('#fadeOut').click(function(){
			$('div').fadeOut(3000,function(){
				$('span').fadeIn(100);
			});
			return false;
		});
		
		$('#fadeToggle').click(function(){
			$('div').fadeToggle(3000,function(){
				$('span').fadeIn(100);
			});
			return false;
		});
	});
	//요소의 현재 표시상태에 따라 다른 동작을 하는 .fadeToggle()메소드 사용가능
	//선택 요소가 현재 사라진 상태라면 .fadeIn()메소드 동작 수행
	//나타나 있는 상태라면 .fadeOut()메소드 동작 수행
</script>
</head>
<body>
 <p>
  불투명도를 점점 높여서 보이도록 한다.
  speed를 fast, normal, slow 또는 0이상의 숫자(밀리세컨트 단위)를 준다.
  애니메이션이 끝난 후에 실행할 함수를 지정한다.
  </p>
	  <div><span> S U C C E S S ! </span></div>
  <button id="fadein">fadeIn </button>
  <button id="fadeOut">fadeOut </button>
  <button id="fadeToggle">fadeToggle </button>

</body>
</html>

 

↓결과

 

 

<예시_8>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>엘리먼트에 투명도 값 변경</title>
<style>
	div{width:80px; height:80px;
		margin:3px; float:left;}
	#red{background:red}
	#green{background:green}
	div#blue{background:blue}	
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('#red').click(function(){
			$(this).fadeTo('slow',1);
		});
		$('#green').click(function(){
			$(this).fadeTo("slow",0.5);
		});
		$('div#blue').click(function(){
			$(this).fadeTo("2000",0);
		});
	});
	//fadeTo() : 대상 엘리먼트를 지정한 투명도 값으로 변경
	//.fadeTo("시간","투명도"):선택한 요소를 설정한 시간도안 투명도 조절
</script>
</head>
<body>
<div id="red"></div><!--클릭 시 투명도 변경없음  -->
<div id="green"></div><!-- 클릭 시 절반의 투명도로 변경 -->
<div id="blue"></div><!-- 클릭시 투명도 0으로 사라짐 -->
</body>
</html>

 

↓결과

 

 

<예시_9>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>사용자 효과</title>
<style>
	#region{
		position:relative; width:200px; height:200px;
		overflow:hidden; margin:auto;
	}
	#images{width:400px; height:200px;}
	#images a img{width:200px; height:200px; 
					border:0; position:realtive;}
	#direction{width:360px; margin:auto;}
	.leftbtn{margin-top:10px;}
	.rightbtn{margin-left:290px; margin-top:10px;}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('.leftbtn').click(function(event){
			$('#leftimage').animate({marginLeft:-210}, 2000);
		});
		$('.rightbtn').click(function(event){
			$('#leftimage').animate({marginLeft:0}, 2000);
		});
	});
	//animate():엘리먼트를 나타나게 하거나 감추기를 반복
</script>
</head>
<body>
	<div id="region">
		<div id="images">
			<a href="#"><img id="leftimage" src="../images/im0.jpg"></a>
			<a href="#"><img id="rightimage" src="../images/im1.jpg"></a>
		</div>
	</div>
	<div id="direction">
		<button class="leftbtn">&laquo;</button>
		<button class="rightbtn">&raquo;</button>
	</div>
</body>
</html>

 

↓결과

 

 

<예시_10>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>자바스크립트 배열</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		var list=['aaa','bbb','ccc','ddd','eee'];
		$('#log').text(list.join(', '));
		console.log(list);
	})
</script>
</head>
<body>
	<div id="log"></div>
</body>
</html>

 

↓결과

 

 

<예시_11_1>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>자바스크립트 객체</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		//자바 스크립트에서 객체 생성하기
		var car = new Object();
		//객체를 구성하는 요소
		car.make='aaa';
		car.model='bbb';
		car.year='2022';
		
		//Date타입 인스턴스를 하나의 프로퍼티로 지정
		car.buydate=new Date(2022,10,25);
		
		var owner = new Object();
		owner.name="hello";
		owner.age = 27;
		
		//var owner=new Object();모든 객체가 Object객체에서 파생
		//새로운 객체를 만들기 위해서는 new 연산자와 Object()생성자 이용
		
		//프로퍼티의 값이 자바스크립의 객체 car의 멤버로 owner을 넣을 수 있음
		car.owner=owner;
		
		console.log(car.make); //aaa
		console.log(car.model); //bbb
		
		//중첩된 프로퍼티 접근
		console.log(car.owner.name); //hello
	});
</script>
</head>
<body>

</body>
</html>

 

↓결과

console로만 출력하기 때문에  브라우저 창은 빈 창

 

 

<예시_11_2>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>객체 리터럴로 객체 생성</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		//객체 리터럴로 객체 생성
		var car={
				make :'aaa',
				model :'bbb',
				year:2022,
				buydate: new Date(2022,10,25),
				owner:{
					name:'ccc',
					age:27	
				}
		};
		
		console.log(car.make); //aaa
		console.log(car.model); //bbb
		console.log(car.owner.name); //ccc
	});
	//객체 리터럴로 객체 생성하는 방법은 JSON표기법 사용
	//객체는 중괄호의 쌍으로 표시되고 프로퍼티는 중괄호 안에서 쉼표로 나열
</script>
</head>
<body>

</body>
</html>

 

↓결과

 

 

<예시_12>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>배열 반복처리</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		var list=['aaa','bbb','ccc','ddd','eee']
		$.each(list, function(index, value){
			$('ol').append('<li>'+value+'</li>');
		});
	});
	//$.each() : DOM엘리먼트 확장 집합의 엘리먼트를 순회하는 each()메소드가 있음
	//				배열과 객체를 순회할 목적으로 $.each() 유틸리티 함수 제공
	//$.each(list, function(index, value)) 
	//	반복 구조를 갖는 배열 형태의 첫번째 매개변수에 해당하는 값을 넣고
	// 두번째 매개변수에서 콜백 함수 처리
</script>
</head>
<body>
<ol>	</ol>
</body>
</html>

 

↓결과

 

 

<예시_13>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>배열에서 특정조건의 요소만 선택하여 반환</title>
<style>
	*{font-size:20pt; font-weight:bold}
	div{color:blue;}
	p{color:green; margin:0}	
	span{color:red}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		var arr=[1,9,3,8,6,1,5,9,4,7,3,8,6,9,1];
		$('div').text(arr.join('; '));
		
		arr=$.grep(arr, function(element, index){
			return (element !=5 && index >4);
		});
		$('p').text(arr.join(', '));
		 
		arr = $.grep(arr, function(element){
			return element !=9;
		});
		$('span').text(arr.join(", "));
		
		arr =$.grep(arr, function(element){
			return element >5
		});
		$('#kbs').text(arr.join(", "));
	});
	//$.grep() : 반복 구조를 갖는 배열 형태의 첫번째 매개변수에서
	//			해당하는 값을 받아 filtering하고 그 결과를 배열형태로 반환
</script>
</head>
<body>
<div></div>
<p></p>
<span></span>
<div id="kbs"></div>
</body>
</html>

 

↓결과

 

 

<예시_14>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>객체 맵 형식을 자바스크립트 배열화하기</title>
<style>
	div{color:red;}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('button').click(function(){
			var elems = $('div');
			var arr= $.makeArray(elems);
			arr.reverse();
			$(arr).appendTo(document.body);
		});
	});
	//$.makeArray(): 반복 구조를 갖는 배열 형태의 객체 Array객체로 변형
	//reverse(): 역순 재배치
</script>
</head>
<body>
<button>click</button>
<div>first</div>
<div>second</div>
<div>three</div>
<div>fifth</div>
<div>해바라기</div>
</body>
</html>

 

↓결과

 

 

<예시_15>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>InArray()</title>
<style type="text/css">
div {
	color: blue
}

span {
	color: red
}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function() {
		var arr = [ 1, 'four', 3, 'two' ];
		var $spans = $('span');
		$spans.eq(0).text($.inArray("one", arr));
		$spans.eq(1).text($.inArray(2, arr));
		$spans.eq(2).text($.inArray(3, arr));
		$spans.eq(3).text($.inArray("four", arr, 2));
	});
	//$.inArray():배열에 값이 존재하는지 살펴서 몇번째 index에 존재하는지 확인가능
	//			 존재하지 않으면 -1 return
	//.inArray(value, array[, fromIndex])
	//		value:검색하고자하는 값
	// 		array:배열의 이름 입력
	//			fromIndex : 선택사항, 몇번째 배열값부터 검색할지 정함
	// 						기본값 0, 첫번째배열부터 검색
</script>
</head>
<body>
	<div>
		"one" 검색 결과 : <span></span>
	</div>
	<div>
		2 검색 결과 : <span></span>
	</div>
	<div>
		3 검색 결과 : <span></span>
	</div>
	<div>
		"four" 검색 결과 : <span></span>
	</div>
</body>
</html>

 

↓결과

 

 

<예시_16>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>$.map()</title>
<style type="text/css">
	*{font-size:14pt; font-weight:bold}
	div{color:blue}
	p{color:green; margin:0;}
</style>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		var months=['sunday','monday','tuesday','wedensday','thursday','friday','saturday'];
		var mons=$.map(months, function(value, indexOrkey){
			return value.substr(0,3);
	});
		
		$('div').text(months.join(", "));
		$('p').text(mons.join(", "));
	});
	
	//$.map() : 값의 집합을 다른 집합으로 변환하는 연산
	//$.map() 1번째 매개변수에 요일명을 지정한 months 배열을 전달
	//			2번째 매개변수인 익명 함수가 각 배열 요소를 반복하면서 호출
	// value.substr(0,3) : 배열의 각 요소 값에서 처음 3글자만 얻어내서 mons 배열에 저장
</script>
</head>
<body>
<div></div>
<p></p>
</body>
</html>

 

↓결과

 

 

<예시_17>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>객체 확장하기</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
	$(function() {
		var settings = {
			name : 'defaultName',
			size : 5,
			global : true
		};
		var options = {
			name : "korea",
			size : 10
		};

		console.log("before extend settings : ");
		console.log(settings);
		console.log("options : ");
		console.log(options);

		$.extend(settings, options);

		console.log("after extend settings : ");
		console.log(settings);
	});
	//$.extend() : 여러개의 객체를 합한다. 동일한 프로퍼티가 있는 경우 뒤에 있는것이 우선
	//settings 변수에 저장된 프로퍼티에 options변수에 저장된 프로퍼티를 확장
</script>
</head>
<body>

</body>
</html>

 

↓결과