2020.11.16 javascript 수업노트

할인률



<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<link rel="stylesheet" href="../css/public.css">

<style>

.box div { /* 전체 div를 가리키지만 밑에서 사진1개박스랑 사진4개박스 스타일을 지정해줘서 가장 큰 애만 이거가 적용되는듯 */

height: 200px;

width: 690px;

}


.box .guess_box { /* 사진한개 들어있는 박스  */

width: 150px;

height: 130px;

float: left;

margin: 3px;

padding: 3px;

background: #87CEEB;

}


img {

width: 100%;

height: 90px;

}



img:hover {

border : 2px solid green;


}


result1 { /* 사진 4 개 들어있는 박스  */

height: 200px;

}

</style>


<script>



//window 에 onload 됬을때 function 을 수행해라... ! ( 사진이 만들어지지 않은 상태에서 하면 안됨 )

// 밑에 있는 body 태그가 모두 실행되고 나서 함수가 실행된다. 

window.onload = function() { 

// <img class="cimg" src="../images/이탈리아.jpg" alt="이탈리아"> 여기있는 cimg 클래스 모두 선택해서 가져오기 (여러개다. )

vimgs = document.querySelectorAll('.cimg'); 

for(i = 0 ; i < vimgs.length ; i++) { 

//사용자정의 함수를 만들어준것 

//함수옆에 proc2() 이렇게 괄호를 붙여주지 않아도 된다. 

vimgs[i].addEventListener('click' , proc2)

}

}



ptag2 = null; 

 function proc2() {

//this 바로 사용할 수 있다. 

 

 

if (ptag2 != null ){

 

//자식요소 

pp2 = document.getElementsByClassName("pp2")[0]; 

//부모요소

guessBox = ptag2.parentNode;

guessBox.removeChild(pp2); 

}

 

 

//랜덤발생 5 ~ 10 

rand = Math.floor(Math.random() * 6  + 5 ); 

 

// textNode생성 - 할인율 : 10% 

 

text = document.createTextNode("할인율 : " + rand + "%"); 

 

//p태그 생성 이 p 태그는 글씨가 들어가 있는것.. 

 

ptag2 = document.createElement("p"); 

//ptag 에 class 를 생성해 준것. 

ptag2.setAttribute('class', 'pp2'); 

//p태그에 textNode 추가한다. 

 

ptag2.appendChild(text); 

 

 

 

// guess_box 에다가 p 태그 추가 

 

//img 를 this 사용한다. 

// vimg 의 부모요소(guess_box) 를 찾으면 된다. 

 

this.parentNode.appendChild(ptag2);  

 

 }






 ptag = null; 

 function proc1(vimg) {  //vimg 는 this 로 가져온 이미지부분 . 

 

//ptag = document.getElementsByClassName("pp"); 

//vimg.parentNode.removechild(pta);

 

 

if (ptag != null ){

pp = document.getElementsByClassName("pp")[0]; 

guessBox = ptag.parentNode;

guessBox.removeChild(pp); 

}

 

 

//랜덤발생 5 ~ 10 

rand = Math.floor(Math.random() * 6  + 5 ); 

 

// textNode생성 - 할인율 : 10% 

 

text = document.createTextNode("할인율 : " + rand + "%"); 

 

//p태그 생성 이 p 태그는 글씨가 들어가 있는것.. 

 

ptag = document.createElement("p"); 

//ptag 에 class 를 생성해 준것. 

ptag.setAttribute('class', 'pp'); 

//p태그에 textNode 추가한다. 

 

ptag.appendChild(text); 

 

 

 

// guess_box 에다가 p 태그 추가 

 

//img 를 this 로 아래에서 넘겨받아 vimg 변수로 proc1 함수에서 받았다. 

//vimg 가 클릭한 이미지이고, 그것의 부모인 div ( guess_box ) 에 넣으려면 

// vimg 의 부모요소(guess_box) 를 찾으면 된다. 

 

//ptag.removeChild(ptag); 

vimg.parentNode.appendChild(ptag);  

 

 }


 





</script>








</head>

<body>

<div class="box"> <!-- 연보라색상페이지 -->

<h3>할인률</h3>

&lt;img onclick="proc1(this)" src="../images/이탈리아.jpg" alt="이탈리아">

이미지를 클릭하면 p태그를 생성 , guess_box 에 p 태그를 추가 <br>

&lt;p class="pp">할인율 : 10% &lt;/p> <br> 할인율은 5 ~ 10 사이의 난수를 발생한다. <br>

<div id="result1"> <!-- 사진 4개들어있는 페이지 -->

<div class="guess_box"> <!-- 사진 1개들어있는 작은 박스  -->

<img onclick="proc1(this)" src="../images/이탈리아.jpg" alt="이탈리아">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/오로라.jpg" alt="오로라">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/여행.jpg" alt="여행">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/에스프레소.jpg" alt="에스프레소">

</div>

</div>

</div>

<div class="box"> <!-- 연보라색상페이지 -->

<h3>할인률</h3>

이미지를 클릭하면 p태그를 생성 , guess_box 에 p 태그를 추가 <br>

이벤트 일괄처리 

vimgs = document.getElementByClassName('cimg');

vimg = document.querySelectorAll('.cimg');

for(i = 0 ; i < vimgs.length ; i++){

vimgs[i].addEventListener('click', proc2);

}


<div id="result2"> <!-- 사진 4개들어있는 페이지 -->

<div class="guess_box"> <!-- 사진 1개들어있는 작은 박스  -->

<img class="cimg" src="../images/이탈리아.jpg" alt="이탈리아">

</div>

<div class="guess_box">

<img class="cimg" src="../images/오로라.jpg" alt="오로라">

</div>

<div class="guess_box">

<img class="cimg" src="../images/여행.jpg" alt="여행">

</div>

<div class="guess_box">

<img class="cimg" src="../images/에스프레소.jpg" alt="에스프레소">

</div>

</div>

</div>




</body>

</html>



-----------------------------------------------------------------------------------------------------

 데이터 검증 


<<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<link rel="stylesheet" href="../css/public.css">

<style>

</style>


<script>


 function proc1() {//body 가 완료된 후에 브라우저에 뜬 뒤에 실행하라 

/* ff = document.getElementById('ff');

// 또는 ff = document.querySelector('#ff');  */

vname = document.getElementById('name').value; 

addr = document.getElementById('addr').value;

bir = document.getElementById('birthday').value; 

mail = document.getElementById('email').value; 

id = document.getElementById('userid').value; 

tel = document.getElementById('phone').value; 

pass = document.getElementById('pass').value;

nvalue = vname.trim().length;

avalue = addr.trim().length;

bvalue = bir.trim().length;

mvalue = mail.trim().length;

ivalue = id.trim().length;

tvalue = tel.trim().length;

pvalue = pass.trim().length; 

  //이름입력을 안했거나, 이름에 공백만 보냈을떄 다시 입력하도록 한다. 

  if  (nvalue < 1) { 

alert("이름 입력 ");ㅣ

return false; 

}

//이름길이는 2자리에서부터 4 사이로 하게 한다. 

if(nvalue < 2||nvalue > 4){

alert("이름 2~4 사이로 입력하시오"); 

return false; 

}

//정규식 체크 

nameReg = /^[가-힣]{2,4}$/; 

 

if(!(nameReg.test(vname))){

alert("이름 형식 오류..");

return false; //함수를 종료한다.  

}

 

//주소입력 공백제거

if ( avalue < 1 ) { 

alert("주소 입력 ");

return false; 

}

//생일입력 공백제거

if ( bvalue < 1 ) { 

alert("생일 입력 ");

return false; 

}

//아이디 입력 공백제거 - 6 ~ 8 

if ( ivalue < 1 ) { 

alert("아이디 입력 "); 

return false; 

}

//아이디길이 6 ~ 8 

if ( ivalue < 6 || ivalue > 8) { 

alert("아이디 6 ~ 8 글자를 입력하세요"); 

return false; 

}

//아이디 정규식 - 영문 소문자로 시작한다. 

idReg = /^[a-z][a-zA-Z0-9]{5,7}$/;

if(!(idReg.test(id))){

alert("아이디형식오류")

return false; 

}

 

//비밀번호 - 공백 

if(pvalue < 1 ) {

alert("비밀번호를 입력하세요");

return false; 

}

//비밀번호 길이 8 ~ 15 자리

if(pvalue < 8 || pvalue > 15 ){

alert("8보다 작고 15보다 작은 비밀번호를 입력해 주세요")

return false; 

}

 

///////////////////////////////////////////////////////////////////////////////////////////////

 

/*  //전방탐색 

// 검색문자?=기준문자 : 기준문자를 기준으로 해서 전방(앞의)탐색으로 검색한다. 

//a = http://www.naver.com   , https://www.daum.net 

//http 인지 https 인지 비교 - 해당 문자를 직접 가져온다. - value.match(reg)

//match() 수행후 해당 문자가 있으면  -> 문자를 가져오고 없으면 null 을 리턴한다.  

a = "http://www.naver.com" ; 

a2 = "https://www.daum.net" ; 

reg = /\w+(?=:)/

b = a2.match(reg); 

if(b == "http"){

alert("http 요청입니다.");

}else if ( b == "https"){

alert("https 요청입니다.");

}

//////////////////////////////////////////////////////////////////////////  */

 

//정규식 - 전방탐색 응용 - 영문소문자대문자숫자특수문자가 반드시 한개이상씩 포함  

passReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&]).{8,15}$/;

 

if(!(passReg.test(pass))){

alert("비밀번호 형식오류"); 

return false; 

}

 

 

//메일입력 공백제거

if ( mvalue < 1 ) { 

alert("메일 입력 "); 

return false; 

}

//이메일 정규식 

mailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z]+){1,2}$/

if(!(mailReg.test(mail))){

alert("이메일형식오류");

return false; 

}

//전화번호 입력 공백제거

if ( tvalue < 1 ) { 

alert("전화번호 입력 ")

return false; 

}

//전화번호 정규식 

telReg = /\d{2,3}-\d{4}-\d{4}/

if(!(telReg.test(tel))) {

alert("전화번호 형식오류")

return false; 


}  //if 끝 

 

 

alert("성공");


 }

</script>






</head>

<body>

<div class="box">

<h3>데이타 길이/ 공백 검증</h3>

trim() : 앞 뒤 공백을 제거 <br> length <br>


<h3>정규식 : 일정한 규칙에 따라 데이터를 입력</h3>

정규식패턴.test(입력값) - return 결과형 true / false <br>




<h3>회원가입</h3>

//밑에서 submit 을 누르면 test.jsp 로 가는데 곧장 jsp 로 가지않게 하려고 onsubmit="return

false; 를 쓴다."

<form id="ff" action="test.jsp" method="post" onsubmit="return false">

이름: <input type='text' id='name'><br> 

주소: <input type='text' id='addr'><br> 

생일: <input type='date' id='birthday'><br> 

아이디(6-8 문자): <input type='text' id='userid'><br> 

비밀번호 : <input type='text' id="pass"><br>

이메일: <input type='email' id='email'><br>

휴대폰: <input type='tel' id='phone'><br> 

 

<input type='button' onclick="proc1()" value='확인'><br>

</form>


</div>




</body>


</html>



test.jsp 



<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html >

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

 <h1>jsp : Java Server Page</h1>



</body>

</html>


dom돔추가삭제 



<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<link rel="stylesheet" href="../css/public.css"> 

<style>

</style>

<script>

 

 str = ["넥타린", "허니" , "복숭아", "엠버" , "카시스"];

 

 function proc1() {

 

  index1 = Math.floor(Math.random() * str.length);

 

//랜덤발생 str[0], str[4] , str[6]

 

 

//선택된 문자열로 textNode 를 생성한다. 

text = document.createTextNode(str[index1]); 

 

//p태그 생성

 

ptag = document.createElement("p") ; 

 

//text 를 ptag에 추가한다. 

 

ptag.appendChild(text); 

 

//result1 에 ptag를 추가한다. 

 

result1 = document.getElementById('result1');

result1.appendChild(ptag);

 

 }


 

 function proc2() {

//부모요소를 가져오기 result1 

result1 = document.getElementById('result1');

 

//부모요소, 첫번쨰(마지막)자식을 얻는다

 

child = result1.firstChild;

 

//삭제 - 부모요소.removeChild(자식요소)

 

result1.removeChild(child); 

 }

 

 

 function proc3(){

 

//랜덤발생 배열 1개 뽑기

index1 = Math.floor(Math.random() * str.length);

text = document.createTextNode(str[index1]); 

//p태그 생성해서 위에 배열에서 랜덤으로 뽑은애 1개를 ptag에 넣어줌 

 

ptag = document.createElement('p') ; 

ptag.appendChild(text);

 

// input 타입 요소를 가져옴 버튼타입이다. 삭제라는 이름을 가지고 있다. 

btag = document.createElement("input");

btag.type ="button";

btag.value ="삭제"; 

  btag.onclick= function(){

  //현재노드(button) 의 부모노드를 반환 

  //parentp = this.parentNode;

  //parentp 는 result3 의 자식 btag 의 부모 ( btag현재 누른것을 this 로 받는다. )

  this.parentNode.remove();

 

//result3.remove(btag.parentNode);

  } ;  

 

 

//ptag 에 위에 만든 buttontag 를 넣어준다. 

ptag.appendChild(btag); 

 

//result3 div 를 불러온다.

result3 = document.getElementById('result3');

//위에서 만들어진 ptag를 넣어준다. 

result3.appendChild(ptag);

 

 

 

 

 }

 



</script>




</head>

<body>

<div class="box">

<h3>제목</h3>

추가 : 배열로 문자열 생성 , 랜덤 발생으로 문자열을 선택한다. <br>

선택한 문자열로 textnode를 생성한다. 

p 태그를 생성 - createElement("p")<br>

p태그의 자식요소로 textnode 를 추가한다. 추가한다.<br> 

result1의 자식요소로 p 테그를 추가한다. <br>

삭제 :

child = result1.lastChild; <br> 

result1.removeChild(child); <br> 

<input type="button" value="추가" onclick="proc1()"> <br> <br>

<input type="button" value="삭제" onclick="proc2()"> <br> <br>

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

<div id="result2"></div>

</div>

<div class="box">

<h3>추가/생성</h3>

추가 : 배열로 문자열 생성 , 랜덤 발생으로 문자열을 선택한다. <br>

선택한 문자열로 textnode를 생성한다.<br>

button 요소를 생성한다. -> createElement('input')<br>

p 태그를 생성 - createElement("p")<br>

p태그의 자식요소로 textnode 와 button 요소를 추가한다.<br>

 

result3의 자식요소로 p 테그를 추가한다. <br>

삭제 :

자식요소.remove() : 부모요소에서 선택한 자식 요소를 삭제한다.  

<input type="button" value="추가/삭제" onclick="proc3()"> <br> <br>

<div id="result3"></div>


</div>




</body>

</html>




할인률 


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<link rel="stylesheet" href="../css/public.css">

<style>

.box div { /* 전체 div를 가리키지만 밑에서 사진1개박스랑 사진4개박스 스타일을 지정해줘서 가장 큰 애만 이거가 적용되는듯 */

height: 200px;

width: 690px;

}


.box .guess_box { /* 사진한개 들어있는 박스  */

width: 150px;

height: 130px;

float: left;

margin: 3px;

padding: 3px;

background: #87CEEB;

}


img {

width: 100%;

height: 90px;

}



img:hover {

border : 2px solid green;


}


result1 { /* 사진 4 개 들어있는 박스  */

height: 200px;

}

</style>


<script>



//window 에 onload 됬을때 function 을 수행해라... ! ( 사진이 만들어지지 않은 상태에서 하면 안됨 )

// 밑에 있는 body 태그가 모두 실행되고 나서 함수가 실행된다. 

window.onload = function() { 

// <img class="cimg" src="../images/이탈리아.jpg" alt="이탈리아"> 여기있는 cimg 클래스 모두 선택해서 가져오기 (여러개다. )

vimgs = document.querySelectorAll('.cimg'); 

for(i = 0 ; i < vimgs.length ; i++) { 

//사용자정의 함수를 만들어준것 

//함수옆에 proc2() 이렇게 괄호를 붙여주지 않아도 된다. 

vimgs[i].addEventListener('click' , proc2)

}

}



ptag2 = null; 

 function proc2() {

//this 바로 사용할 수 있다. 

 

 

if (ptag2 != null ){

 

//자식요소 

pp2 = document.getElementsByClassName("pp2")[0]; 

//부모요소

guessBox = ptag2.parentNode;

guessBox.removeChild(pp2); 

}

 

 

//랜덤발생 5 ~ 10 

rand = Math.floor(Math.random() * 6  + 5 ); 

 

// textNode생성 - 할인율 : 10% 

 

text = document.createTextNode("할인율 : " + rand + "%"); 

 

//p태그 생성 이 p 태그는 글씨가 들어가 있는것.. 

 

ptag2 = document.createElement("p"); 

//ptag 에 class 를 생성해 준것. 

ptag2.setAttribute('class', 'pp2'); 

//p태그에 textNode 추가한다. 

 

ptag2.appendChild(text); 

 

 

 

// guess_box 에다가 p 태그 추가 

 

//img 를 this 사용한다. 

// vimg 의 부모요소(guess_box) 를 찾으면 된다. 

 

this.parentNode.appendChild(ptag2);  

 

 }






 ptag = null; 

 function proc1(vimg) {  //vimg 는 this 로 가져온 이미지부분 . 

 

//ptag = document.getElementsByClassName("pp"); 

//vimg.parentNode.removechild(pta);

 

 

if (ptag != null ){

pp = document.getElementsByClassName("pp")[0]; 

guessBox = ptag.parentNode;

guessBox.removeChild(pp); 

}

 

 

//랜덤발생 5 ~ 10 

rand = Math.floor(Math.random() * 6  + 5 ); 

 

// textNode생성 - 할인율 : 10% 

 

text = document.createTextNode("할인율 : " + rand + "%"); 

 

//p태그 생성 이 p 태그는 글씨가 들어가 있는것.. 

 

ptag = document.createElement("p"); 

//ptag 에 class 를 생성해 준것. 

ptag.setAttribute('class', 'pp'); 

//p태그에 textNode 추가한다. 

 

ptag.appendChild(text); 

 

 

 

// guess_box 에다가 p 태그 추가 

 

//img 를 this 로 아래에서 넘겨받아 vimg 변수로 proc1 함수에서 받았다. 

//vimg 가 클릭한 이미지이고, 그것의 부모인 div ( guess_box ) 에 넣으려면 

// vimg 의 부모요소(guess_box) 를 찾으면 된다. 

 

//ptag.removeChild(ptag); 

vimg.parentNode.appendChild(ptag);  

 

 }


 





</script>








</head>

<body>

<div class="box"> <!-- 연보라색상페이지 -->

<h3>할인률</h3>

&lt;img onclick="proc1(this)" src="../images/이탈리아.jpg" alt="이탈리아">

이미지를 클릭하면 p태그를 생성 , guess_box 에 p 태그를 추가 <br>

&lt;p class="pp">할인율 : 10% &lt;/p> <br> 할인율은 5 ~ 10 사이의 난수를 발생한다. <br>

<div id="result1"> <!-- 사진 4개들어있는 페이지 -->

<div class="guess_box"> <!-- 사진 1개들어있는 작은 박스  -->

<img onclick="proc1(this)" src="../images/이탈리아.jpg" alt="이탈리아">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/오로라.jpg" alt="오로라">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/여행.jpg" alt="여행">

</div>

<div class="guess_box">

<img onclick="proc1(this)" src="../images/에스프레소.jpg" alt="에스프레소">

</div>

</div>

</div>

<div class="box"> <!-- 연보라색상페이지 -->

<h3>할인률</h3>

이미지를 클릭하면 p태그를 생성 , guess_box 에 p 태그를 추가 <br>

이벤트 일괄처리 

vimgs = document.getElementByClassName('cimg');

vimg = document.querySelectorAll('.cimg');

for(i = 0 ; i < vimgs.length ; i++){

vimgs[i].addEventListener('click', proc2);

}


<div id="result2"> <!-- 사진 4개들어있는 페이지 -->

<div class="guess_box"> <!-- 사진 1개들어있는 작은 박스  -->

<img class="cimg" src="../images/이탈리아.jpg" alt="이탈리아">

</div>

<div class="guess_box">

<img class="cimg" src="../images/오로라.jpg" alt="오로라">

</div>

<div class="guess_box">

<img class="cimg" src="../images/여행.jpg" alt="여행">

</div>

<div class="guess_box">

<img class="cimg" src="../images/에스프레소.jpg" alt="에스프레소">

</div>

</div>

</div>




</body>

</html>





댓글