Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

노승현

JavaScript 본문

JavaScript

JavaScript

nsh95 2024. 1. 5. 08:25

 

 

선언함수 : 어떠한 기능을 여러번 사용하기 위해 만든 함수

 스크립트 함수이기 때문에 선언한 뒤 사용해야 한다.

 

 

익명함수 : 

기능을 한 번만 사용할 때 사용

변수에 저장하여 쓴다.

해당변수를 호출해서 쓴다.

 

 

 

 <!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
</head>

<body>
	<script>
		console.log('브라우저 콘솔');

		var num1 = 10;
		var num2 = 20;
		var num3 = num1 + num2;
		console.log('num3 = ' + num3);


		var ans1 = prompt('입력하세요!');
		console.log('ans1 = ' + ans1);
		var ans2 = confirm('Yes or No ? ');
		console.log('ans2 = ' + ans2);
		alert('알림창');

		var res;
		console.log('res = ' + res);
		// 값이 없는 것을 출력하려고 할 땐 undefined
		// 로그를 잘 찍어보자

		var a = 9;
		var b = '9';

		console.log('a==b');
		console.log(a == b);
		console.log('a===b');
		console.log(a === b);

		// 웹은 거의 문자열로 취급



	</script>


</body>

</html>

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문제 풀이</title>
</head>
<body>
   
   <script>
      while(true){
         var ans=prompt('나이를 입력하세요.');
         console.log('ans의 자료형 : '+typeof ans);
         if(0<ans && ans<=120){
            break;
         }
         alert('1~120 사이의 값으로 입력하세요!');
      }
      var money=0;
      if(8<ans && ans<20){
         money=1200;
      }
      else if(20<=ans && ans<=65){
         money=2000;
      }
      document.write(money+'원입니다.');
   </script>

</body>
</html>

 

 

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
</head>

<body>

	<script>
		while (true) {
			var age = prompt('나이를 입력해주세요 1~120살까지 입력 가능합니다.');
			console.log('age=' + typeof age)
			if (age >= 1 && age <= 120) {
				break;
			}
			continue;
			alert('1~120 사이의 값으로 입력해라');
		}


		var money = 0;
		if (age <= 8) {
			alert('가격은 0원입니다.');
			console.log('가격은 0원입니다.');
			document.write('가격은 0원입니다.');
		} else if (age >= 9 && age <= 19) {
			alert('가격은 1200원입니다.');
			console.log('가격은 1200원입니다.');
			document.write('가격은 1200원입니다.');
		}
		else if (age >= 20 && age <= 65) {
			alert('가격은 2000원입니다.');
			console.log('가격은 2000원입니다.');
			document.write('가격은 2000원입니다.');
		}
		else {
			alert('가격은 0원입니다.');
			console.log('가격은 0원입니다.');
			document.write('가격은 0원입니다.');
		}



	</script>



</body>

</html>

 

 

<!--내장 함수-->
<script>
	var str = 'banana';
	console.log(str.charAt(0));			// 0번째는 무슨글자가 있니
	console.log(str.indexOf('a'));		// 몇번째 인덱스에 있니
	console.log(str.lastIndexOf('a'));	// 마지막 a가 몇 번째 인덱스에 있나?
	console.log(str.substring(1,3));	// 1번부터 3번전까지 보여줘
	console.log(str.replace('a','A'));	// a 를 A로 바꿔줘
	console.log(str.toUpperCase());		// 전부다 대문자로 바꿈
</script>


36~41 : 내장 객체 String 의 메서드를 사용중 ...
Math : 주로 랜덤 값을 생성할 때에 활용됨
Date : 날짜와 관련된 작업을 수행할 때에 활용됨

 

 

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
</head>

<body>

	<script>
		// 1~100 사이에 랜덤값을 뽑아서 저장
		// 입력을 받는 값을 저장해
		// 두번째 입력 받은 값은 -1
		// if 사이의 값이면 


		var rand = Math.floor(Math.random() * 100) + 1;
		var min = 1;
		var max = 100;
		while (true) {
			var result = prompt(min + '~' + max + '사이의 숫자를 입력해주세요');
			result = parseInt(result);	// string 을 int 타입으로 바꿔줌 
			if (result > rand) {
				alert('down');
				max = result - 1;
			}
			else if (result < rand) {
				alert('up');
				min = result + 1;
			}
			else if (rand == result) {
				alert('정답입니다.')
				break;
			}
			continue;



		}
	</script>
</body>

</html>

 

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<style>
		#box {
			background-color: lightcoral;
			cursor: pointer;
			width: 40px;
		}
	</style>
</head>


<body>

	<script>
		window.onload = function () {	// 윈도우가 화면에 로드되었을 때, 전체 글을 다 읽은 다음에 수행하는 코드
			var box = document.getElementById('box');	// 아이디가 박스인 요소를 불러와줘
			box.onclick = function () {
				//alert('이벤트 등록');
				window.open('https://www.naver.com/');
			};

			var list = document.querySelectorAll('#box1 > ul > li');		// id가 없는 요소를 가져올때는 쿼리셀렉터를 사용해서 불러와라
			list[0].style.backgroundColor = 'lightblue';				// selectAll을 쓰면 for 문 사용
			list[1].style.backgroundColor = 'lightblue';				// 스크립트에서는 하이푼을 안쓴다.
		};	
	</script>

	<div id="box">클릭</div>

	<hr>

	<div id="box1">
		<ul>
			<li>베스트 상품</li>
			<li>신상품</li>
		</ul>
	</div>

	<div id="box2">
		<ul>
			<li>후드티</li>
			<li>반팔티</li>
			<li>운동화</li>
		</ul>
	</div>
</body>

</html>

 

 

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>이벤트 등록 02</title>
	<style>
		div {
			width: 50px;
			height: 50px;
			background-color: red;
			left: 200px;
			top: 10px;
		}
	</style>
</head>

<body>

	<script>
		function addElem() {
			var btn = document.getElementById('btn');


			function func() {
				var div = document.createElement('div');

				var a = document.createElement('a');
				var txt = document.createTextNode('링크');
				a.appendChild(txt);
				a.setAttribute('href', 'https://www.naver.com/');

				div.appendChild(a);

				document.body.appendChild(div);
			}

			btn.onclick = func;	//
		}

		addEventListener('load', addElem);

	</script>

	<button id="btn">버튼을 누르면 요소를 생성합니다.</button>

</body>

</html>

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<script>
		window.onload = function(){
			document.joinForm.onsubmit = function(){
				if(!joinForm.mid.value){
					alert('아이디를 입력해주세요');
					joinForm.mid.focus();
					return false;
				};	
				if(!joinForm.mpw.value){
					alert('비밀번호를 입력해주세요');
					joinForm.mpw.focus();
					return false;
				};
			};	
		};
	</script>

	<form name="joinForm" action="다음페이지" method="post">
		아이디 : <input type="text" name="mid">	<br>
		비밀번호 : <input type="password" name="mpw">	<br>
		<input type="submit" value="회원가입">
	</form>

</body>
</html>