Java Script/Java Script 수강일지

[수강일지 38] view

jamk-diary 2026. 7. 2. 17:52
Sample 3
view one 으로 이동해서 버튼들 클릭하면 기능 실행되게 만들수 있다 
viewOne

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>viewOne</title>
</head>
<body >

<h1>viewOne</h1>

<a href="./viewTwo.html">view two로 이동</a>


<script type="text/javascript">

	document.bgColor="#ff0000"; //배경변경

	
	
</script>
</body>
</html>
viewTwo

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body bgcolor="green">
<h1>viewTwo</h1>

<input type="button" value="이전으로" onclick="history.back()"/>

<input type="button" value="페이지 갱신" onclick="location.reload()">

<input type="button" value="(이동했던 페이지)진행" onclick="history.forward()" >

<input type="button" value="view three로 이동" onclick="goPage()"/>  <!-- 함수사용 -->

<script type="text/javascript">
function goPage() {
	location.href = "viewThree.html";
}

</script>
</body>
</html>

 

viewThree

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>viewThree</h1>
</body>
</html>

 

sample 4
웹페이지에서 사용자한테 입력받기 
제대로 된 값 입력 안 하면 경고창 띄우기 
입력 받은 값 콘솔창으로 가져 오기 

deafultmove 누르면 페이지 이동하면서 콘솔창에 기본 값 가져온다 

이유 : <a href="default.jsp?name=홍길동&age=24"> default move</a> 코드 작동 

 

 

빈칸에 입력하면 

이동하면서 콘솔창에 입력한 값이 뜬다 

 

세번째 내용 

이름 입력 안 하면 경고창 뜨게 만들기 

이름 제대로 입력 안하면 경고창 

이름 나이 정확하게 입력해야 콘솔창 에 값을 가져올 수 있다 

 

default.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

    <%
    //이름 나이 넘겨줄 수 있게 만들기 
    	String name = request.getParameter("name");
    
    	int age = Integer.parseInt(request.getParameter("age"));
    
    
    	System.out.println("이름 : " +name);
    	System.out.println("나이 : " +age);
    %>
index
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- 

	link 
	
	Html
	
	//차이점 
	<a href= "Url"		->  단독 사용 묶을 수 없음
	<form action=""     -> <form></form>으로 묶어 줄 수 있다 
	
	java Script
	location.href = ""
	

 -->
 
 <a href="default.jsp?name=홍길동&age=24"> default move</a>
 <br/><br/>
 
 <hr/>
 
 <form action ="default.jsp">
 	<input type="text" name="name" placeholder="이름"/><br/>
 	<input type="text" name="age" placeholder="나이"/><br/>
 	<input type="submit" value="default move"/>
 </form>
 
  <br/><br/>
 
 
  <hr/>
 자바 스크립트 방식
 <br/><br/>
 <input type="text" id="name" placeholder="이름"/><br/>
 <input type="text" id="age" placeholder="나이"/><br/>
 <button type="button" onclick="move()">default move</button>
 
 <script type="text/javascript">
 function move() {
	let name=document.getElementById("name").value;
	let age=document.getElementById("age").value;
	
	//검사하게 만들 수 있음 = 빈칸일 때 진행 못하게 
	//자바 스크립트는 제대로 된 값을 (사용자가 원하는 값을 유저한테 받아서 콘솔로 가져올 수 있게 해 준다 
	if(name.trim() ===''){
		alert('이름을 입력해 주십시오');
		return;
	}
	if(name.trim().length <2){
		alert('이름을 정확히 입력해 주세요');
		return;
		
	}
	location.href = "default.jsp?name=" + name + "&age=" +age;
 }
 
 </script>

</body>
</html>

 

Sample5
마우스 동작에 따른 이벤트 발생하게 만들기 

index
<!-- onxxx -->
<!-- 							handle 처리 -->
<!--  
<button type="button" onclick="func()">button</button>

<script type="text/javascript">
function fun() {
	//핸들링 -> event 에 대한 처리 
}

</script>
-->


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body onload="load()">

<!-- 
	onload (초기값 설정할 때 사용)
 	개발자 도구 콘솔창 가면 확인 가능 
 -->
 
<script type="text/javascript">
	function load() {
	console.log('onload 실행');
	}	
</script>



<!-- 
	onclick
	버튼 클릭하면 console.log('button click'); 문구 개발자 도구 콘솔 확인 가능
	
 -->
 
 
<button type="button" onclick="func()">button</button>
 
 <script type="text/javascript">
 function func() {
	console.log('button click');
}
 
 </script>
 
 <br/> <br/>
 
 <!-- 
 	onblur:커서의 포커스가 이동 
 	 빈칸에 커서 올렸다가 다른데 누르면 콘솔창 console.log('onblur실행');   출력
 
 -->
 name: <input type="text" onblur="isRegName()" size = "10"/><br/>
  <script type="text/javascript">
  function isRegName() {
	console.log('onblur실행');
}
  </script>
  
  
   
 <br/> <br/>
  
 
 
 <!--
  onchange:입력된 값이나 선택된 값이 변경되었을 때 실행 되는 것
  (=valueChange)라고 아이폰 쪽에서는 부른다
 
 
  -->
 
 우편 번호 만들기 
 T: <input type="text" size="5" maxlength="3" onchange="isPostNum(this)">
 -<input type="text" size="5" maxlength="3" onchange="isPostNum(this)">
 
 <script type="text/javascript">
 
 //isPostNum 에는 인풋값이 들어오게 만들기  
 function isPostNum(input) {
	//let post = document.getElementById('post').value; - 방법 1 
	let value = input.value;   //-> 객체를 통으로 가져와서 넣는 방법 2
	//alert(value);
	//alert(input.type);  -> 경고창에 input type 값 가져온다
	
	//숫자가 아닌 문자가 포함되어 있을 경우 
	if(value.match(/[^0-9]/g)){
		alert('숫자가 아닌 문자가 포함되어 있습니다');
	}
}
 </script>
 
 
  <br/> <br/>
  
  
  <select onchange="valueChange()">
 
  	<option>영화보기</option>
  	<option>그림그리기</option>
  	<option>게임하기</option>
  </select>
  
  <script type="text/javascript">
  function valueChange() {
	alert('valueChange()');
}
  
  </script>
  
    <br/> <br/>
  
  <!-- onKeydown. onkeypress 
  텍스트창에 문자 입력하고 빈곳 누르면 콘솔창에 키코드 넘어온다 -->
  <input type = "text" name="title"/>
  
  <script type="text/javascript">
 
  /*
  document.getElementsByName("title")[0].onkeydown = function (event) {
		console.log("keycode:" +event.keyCode);} */
  
		//onkeypress를 써서 다른 키 코드 값이 나온다 
  document.getElementsByName("title")[0].onkeypress = function (event) {
		console.log("keycode:" +event.keyCode);}
  
  </script>
  
  <!-- onMouseDown, onMouseup, onMouseOver, onMouseOut -->
  <input type="image" src="./images/san0.gif" 
   onmousedown="mousedown(this)"
   onmouseup="mouseup(this)"
   onmouseover="mouseover(this)"
   onmouseout="mouseout(this)"/>
   
   
   <script type="text/javascript">
   function mousedown(input) {
	input.src = "./images/san1.gif";
}
   
   function mouseup(input) {
	   input.src = "./images/san0.gif"
}
   
   function mouseover(input) {
	   input.src = "./images/san2.gif"
}
   
   function mouseoutin(put) {
	   input.src = "./images/san0.gif"
}
   
 
   </script>
   
   
     <br/><br/>
   
   <a href = "#" onmouseover="document.box.src='./images/surprise.gif'"  
   			     onmouseout="document.box.src='./images/box.gif'"> <!-- 마우스가 떠나면 박스 이미지 보이게 만들기 마우스가 올라오면 gif 이미지 보이게 만들기   -->    
   		<img alt="" src="./images/box.gif" name="box" />		<!-- 사용자한테 가장먼저 기본으로 보이는 이미지 -->     
   			     
  </a>
 
 
 
</body>
</html>

 

sample 6
유저가 버튼을 누르면 경고창에 문장입니다 출력하게 만들기 

유저가 셀렉트로 선택한 걸 콘솔창에 띄우기 

유저가  추가 버튼 누르고 누른 걸 웹페이지에 출력해주기 

<!DOCTYPE html>
<html> <!-- root tag -->

	<head> <!-- html child node -->
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>

	<body><!-- html child node -->
		
		<!-- body child node -->
		<h3 id ="intro">제목입니다</h3>
		
		<p id ="demo"> 단락입니다</p>
		
		<button type="button" onclick="func()">버튼 </button>
		
		<script type="text/javascript">
			function func() {
				//let intro = document.getElementById('intro').innerHTML;
				let intro = document.getElementById('intro').childNodes[0].nodeValue;
				alert(intro);
			}
		
			
		
		</script>
		
		<br/> <br/>
		
		<select id="car"> <!-- 0번찌 -->
		 <option value=""><!-- 1번찌 -->벤츠</option>  <!-- 4번찌 -->
		 <option>아우디</option>
		 <option>현대</option>
		</select>
			
			
			<button  type = "button" onclick="car()">선택</button>
			
			
			<script type="text/javascript">
				function car() {
					let mycar=document.getElementById("car").childNodes
					//alert(mycar.length);
					alert(mycar[4].text);
				}
			
			</script>
			
			<pre>
			엉뚱하게 7이 나오는 이유 
			
			
			제공해주신 코드에서 
			document.getElementById("car").childNodes를 통해 가져오는 
			childNodes는 HTML 태그(요소)뿐만 아니라 태그 사이의 공백, 줄바꿈(텍스트 노드), 
			그리고 주석까지 모두 포함합니다.
			</pre>
			
			<!-- 추가 버튼 누르면  
				let textNode = document.createTextNode("welcome"); 출력 되게 만들기 
			-->
			
			<div id="div1">
				<p id="p1">Hello</p>
				<p id="p2>">World</p>
			</div>
			
			
			<button type="button" onclick="append()">추가</button>
			
			<script type="text/javascript">
			
				function append() {
					let p_tag = document.createElement("p");
					//p_tag.innerHTML = "WELCOME";
					let textNode = document.createTextNode("welcome");
					p_tag.appendChild(textNode);
					
					let div1 = document.getElementById("div1");
					div1.appendChild(p_tag);
				}
			
			</script>
			
			
			
			
			
			
			
			
	</body>

</html>

 

 

work 

work 1 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	table { border: 2px;
			border-style: solid;
				
}

table, th, td{
		border-style: solid;
		border-width: 3px;
		border-color: purple;	
		
	}
</style>
</head>
<body>

<h1>배열의 연산</h1>
<table>
	<thead>
	 	<tr>
	 		<th>첨자</th> <th>a</th> <th>b</th> <th>a*b을 계산</th>
	 	</tr>
	</thead>
	
	<tbody>
		<tr>
			<th>0</th> 
			<td>5</td> <td >33</td> 
			<td> <input type="button" value="계산결과"  onclick="one()"> </td>
		</tr>
		
		<tr>
			<th>1</th> 
			<td>12</td> <td>14</td> 
			<td><input type="button" value="계산결과"  onclick="two()"></td>
		</tr>
		
		<tr>
			<th>2</th> 
			<td>18</td> <td>65</td> 
			<td><input type="button" value="계산결과"  onclick="three()"></td>
		</tr>
		
	</tbody>
</table>

	<script type="text/javascript">
		
	function one() {
		let a = document.getElementsByTagName("td")[0].innerHTML;
		let b = document.getElementsByTagName("td")[1].innerHTML;
		
		let result= a*b;
		
		alert(result);		
			
		}
	function two() {
		let a = document.getElementsByTagName("td")[3].innerHTML;
		let b = document.getElementsByTagName("td")[4].innerHTML;
		
		let result= a*b;
		
		alert(result);
		
			
		}
	function three() {
		let a = document.getElementsByTagName("td")[6].innerHTML;
		let b = document.getElementsByTagName("td")[7].innerHTML;
		
		let result= a*b;
		
		alert(result);
		
			
		}
	
	</script>




</body>
</html>

 

work 2

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1> 단가 * 수량 알람표</h1>
<table border = "1" >
    <thead>
        <tr>
            <th>갯수 </th>  <th>제품a</th>  <th>제품 b</th> <th> 제품 c</th>
        </tr>
    </thead>
    <tbody id ="tbody"></tbody>
</table>

<script type="text/javascript">
// 1. 단가 변수들을 스크립트 태그 안으로 이동시켰습니다.
let a = 300;
let b = 450;
let c = 520;

let tbody = document.getElementById("tbody");


//       <반복문을 통한 tr , th 만들기>
// 2. array.length 대신 갯수를 몇 번 반복할지 숫자를 지정해줍니다. (예: 1개부터 5개까지)
// 변수 i가 곧 '갯수'가 됩니다.
for (let i = 1; i <= 10; i++) {
    
    let tr = document.createElement("tr"); // tr 태그 블록 생성
                                           //let tr 이라는 변수를 만들어 = 여기에 요소를 넣을 건데 html 에서 tr 태그 블록과 같은 형식으로 만들어 라는 뜻

    // 3. <th> 태그에 현재 갯수(i)를 넣어줍니다.
    let th = document.createElement("th");  
    th.innerHTML = i;                      //우리가 10전까지만 만들게 했으니까 i 가 포문 통해서 10전까지 반복하는 동안 t h 태그 블록을 계속 생성하게 만든것 
    
    // 4. 각 제품별로 [단가 * 갯수]를 계산하여 원을 붙여줍니다.
    //createTextNode 공장 자체는 수학 계산을 할 줄 모릅니다. (글자만 다루는 공장이에요!)
	//자바스크립트라는 똑똑한 비서가 공장에 재료를 넘겨주기 전에 괄호 안을 미리 싹 계산해서 완성품으로 전달해 주기 때문에 코드 안에서 저런 계산이 가능했던 거랍니다!

    let td1 = document.createElement("td");
    td1.appendChild(document.createTextNode((a * i) + "원"));  

    let td2 = document.createElement("td"); 
    td2.appendChild(document.createTextNode((b * i) + "원"));  

    let td3 = document.createElement("td");
    td3.appendChild(document.createTextNode((c * i) + "원")); 

    // 5. 생성한 태그들을 조립하여 표(tbody)에 넣습니다.
    //내가 만든 HTML 부품을 어딘가에 집어넣고 싶을 때는 언제나 appendChild를 사용하시면 됩니다.
    //나는 th 부품을 tr 에 넣을 거야 
    //tr 은 자바 스크립트 안에서 선언한 let tr이야 
    
    tr.appendChild(th);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);

    //html에서 사용한 id는 어디로든 문이야 그래서 서로 연결되어 있어 
    //let tbody 쓰고 도큐먼트.겟일러먼트파이 아이디로 html id 가져와서 사용할 수 있었어 이제 선언 안해도 사용할 수 있게 된거야 
    tbody.appendChild(tr);
}
</script>
</body>
</html>
work3

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>(문제)</h2>

<h2>사나이들의 영화인 탑건은 군인 영화입니다. 그러면 육군, 해군, 공군 중 어느 군의 영화일까요? </h2>

<br/>

<input type="button" value="답을보다" onclick="btnclick()"  >

<br/><br/>


 * 버튼을 한 번 클릭하면 힌트가 표시됩니다. 
 * 버튼을 두 번 클릭하면 답이 표시됩니다. 
 
 
 
<script type="text/javascript">
 let loop=0; //변수 선언  -> "컴퓨터에게 '지금 버튼을 몇 번째 누른 상태인지' 기억하게 만들려고"
 //온클릭을 할 때마다 컴퓨터는 계속해서 자꾸 까먹으니까 변수 상자를 만들어서 몇 번 클릭 했는지 인식하게 만들려고 하는 거

 	function btnclick() {
 		
 		if(loop ==0){
 			alert('힌트');
 		    loop = 1 ;
 		}
 		
 		else if (loop ==1) {
 			alert('해군이지롱');
 		    loop = 2;
		}
 	
 		/*
 		아 위에서부터 실행해서 힌트 경고창으로 띄워주고 루프를 1로 바꾼 것

1. 웹페이지에서 클릭하고 경고창으로 힌트 뜬다
2. 다시 돌아오면 거기다가 1을 더해서 2번째인 정답이 출력되게 만든거지?		
 		
 		
		lf 랑 else if 사용 
		
		 클릭 한 번 했을 때는 조건문으로 들어와서 힌트 경고창 띄우기 실행하고 그 다음 준비 상태가 되는데 else if로 두 번째 클릭을 만들게 되니까
 		*/
	}

</script>
</body>
</html>
work 4 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 문제 </h1>
<h1> 다음 이차 방정식을 해를 구하고 , 그 버튼을 클릭하십시오  </h1>

<br/> 

<h1> x<sup>2</sup> -5x =-6</h1> <!-- 제곱 사용법 x^2 쓰고 싶으면 <sup> 태그 사용하기  -->

<br/>
 
<button type="button" onclick="result(1)">x=1</button>
<button type="button"  onclick="result(2)">x=2</button>
<button type="button"  onclick="result(3)">x=3</button>
<button type="button"  onclick="result(4)">x=4</button>
<button type="button"  onclick="result(5)">x=5</button>
<br/><br/>
답은 두 개얌 
<script type="text/javascript">

	
	//Math -> java 내장 함수 : 수학 전용 계산기 객체 : 야 계산기 불러와 하고 입력하는 명령 
	//어떤 숫자의 제곱근을 구해야 한다 -> 자바스크립트에서는 Math.sqrt() 사용하기 
	//let answer1 = (-b +Math.sqrt(b * b -4 *a*c))
	
	//하지만 나는 구냥 답 선택하게 할 거지롱 -2 랑 -3이 정답이양
	
 function result(x) {
	
		let re = Math.pow(x,2) - (5*x);
		if(re === -6){
			
			 alert("정답");
		}
		else{
			alert("오답");
		}
}
	

</script>
</body>
</html>

 

work 5 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
 table { border: 2px;
 	     border-style:solid;
	
}

table, th, td{
		border-style: solid;
		border-width: 3px;
		border-color: purple;	
		
	}
</style>
</head>

<body>
<h1>포털 사이트 </h1>
"열기 "버튼 클릭하면 홈페이지 새창 열기 
<table>
 	<tr>
 		<th>네이버</th> 
 		<td>https://www.naver.com/</td> 
 		<td><input type="button" value="열기 " onclick="naver()"></td>
 	</tr>
 	
 	<tr>
 		<th>다음</th> 
 		<td>https://www.daum.net/</td> 
 		<td><input type="button" value="열기 " onclick="daum()"></td>
 	</tr>
 	
 	<tr>
 		<th>줌</th> 
 		<td>https://zum.com/</td> 
 		<td><input type="button" value="열기 " onclick="zum()"></td>
 	</tr>
 	
 	
</table>



<script type="text/javascript">

function naver() {
	 location.href="https://www.naver.com";
	
}

function daum() {
	 location.href="https://www.daum.net/";
	
}

function zum() {
	 location.href="https://zum.com/";
	
}

</script>








</body>
</html>
work 6 

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

<style type="text/css">
body{
	background-color: #000;
	color: #fff;
}
</style>

</head>
<body>

<h1>사진들</h1>

<div align="center">
<table>
<tr>
	<td>
		<img alt="" name="out" src="./img/c.jpg" width="260" height="440" border="5"/>
	</td>
	<td valign="top" style="padding-left: 20px">
		사진의 선택<br/>
		<form name="frm">
			<select name="picture" onchange="pictureChange()">
				<option>사진의 선택</option>
				<option value="./img/c.jpg">건물복도</option>
				<option value="./img/d.jpg">성당안</option>
				<option value="./img/e.jpg">성당밖</option>
				<option value="./img/a.jpg">메이지건물</option>
			</select>
		</form>
	</td>
</tr>
</table>
</div>

<script type="text/javascript">
function pictureChange() {
	let index = document.frm.picture.selectedIndex;
	//alert(index);
	
	if(index !== 0){
		document.out.src = document.frm.picture.options[index].value;
	}
}

</script>

</body>
</html>

'Java Script > Java Script 수강일지' 카테고리의 다른 글

[수강일지36] 자바 스크립트  (1) 2026.06.30