TIL 0411

먼지·2024년 4월 10일

Today I Learned

목록 보기
38/89
post-thumbnail

jQuery Class

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>class</title>
</head>
<body>
    <script>
        class Person{
            //클래스 필드
            name = 'Smith';
            //메소드
            getName = function() {
                return this.name;
            };  
        };
        //객체 생성
        const me = new Person();
        
        document.write(me);
        document.write('<br>');

        document.write(me.name);
        document.write('<br>');

        document.write(me.getName());
        document.write('<br>');

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

Class 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>class</title>
</head>
<body>
    <script>
        //클래스 정의
        class Person{
            //생성자
            constructor(name){
                //속성 정의
                //instance property
                this.name = name;
            }
            //메서드
            sayHi() {
                document.write('Hi My name is ' + this.name);
                
            }
            
        }
        //객체 생성
        const me = new Person ('Annie');
        //속성 호출
        document.write(me.name);
        document.write('<br>');
        //메서드 호출
        me.sayHi();
        document.write('<br>');
        //정적 메서드 호출
        Person.sayHello();
    </script>
</body>
</html>

Class 3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>class</title>
</head>
<body>
    <script>
        //부모 클래스 정의
        class Animal{
            //생성자
            constructor(age, weight){
                this.age = age;
                this.weight = weight;
            };
            //메소드 정의
            eat() {
                return "eat";
            }
            move(){
                return"move";
            }
        }
        //자식 클래스 정의 (부모 클래스를 자식 클래스에 상속)
        class Bird extends Animal{
            fly(){
                return 'fly';
            }
        }
        //자식 클래스 객체 생성
        const bird = new Bird(1,5);

        document.write(bird.age + '<br>');
        document.write(bird.weight + '<br>')
        document.write(bird.eat()+ '<br>')
        document.write(bird.move()+ '<br>')
        document.write(bird.fly()+ '<br>')
    </script>
</body>
</html>

jQuery Default()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>기본 이벤트</title>
    <script>
        window.onload = function() {
            const alink = document.getElementById('alink');
            //이벤트 연결
            alink.onclick = function() {
                alert('이벤트 연결');
                //기본 이벤트 제거하기
                return false;
            }

            const myForm = document.getElementById('myForm');
            myForm.onsubmit = function(){
                const name = document.getElementById('name');
                alert(name.value);
                //기본 이벤트 제거
                return false;
            }
        }
    </script>
</head>
<body>
    <a id="alink" href="https://www.naver.com">이동</a>
    <form action="a.jsp" id="myForm" method="post">
        이름 <input type="text" name="name" id="name">
        <input type="submit" value="전송">
    </form>
</html>

jQuery Propagation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>이벤트 전달</title>
    <script>
        /*
        이벤트 전파(전달) : 특정 태그에서 이벤트가 발생하면 다른 태그로 이벤트가 전달되는 현상

        이벤트 버블링 : 자식 노드에서 부모 노드 순으로 이벤트를 실행하는 것을 의미
        div
        |               ^
        div             |
        |                |      부모 태그로 이벤트 전파
        p                |
        |
        span        <----- 이벤트 발생
        이벤트 캡쳐링 : 부모 노드에서 자식 노드 순으로 이벤트를 실행하는 것을 의미
        */

        window.onload = function() {
            //이벤트 연결
            document.getElementById('space').onclick = function() {
                alert('space');
                this.style.background = 'pink';
            };
            document.getElementById('paragraph').onclick = function(event){
                alert('paragraph');
                this.style.background = 'yellow';

                //이벤트 전달 제거
                event.stopPropagation();
            };
        }
    </script>
</head>
<body>
    <div id="space">Space
        <p id="paragraph">Paragraph</p>
    </div>
</body>
</html>

jQuery DOM

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>표준 이벤트 모델</title>
    <script>
        /*
        DOM Level 2 표준 이벤트 모델
        addEventListener(eventName, handler, useCapture) : 이벤트 연결
        removeEventListener(eventName, handler) : 이벤트 제거
        */
       //윈도우가 로드될 때 매개 변수로 전달된 함수를 실행
       window.addEventListener('load', function(){
        const header = document.getElementById('header');
       //이벤트 연결
       header.addEventListener('click', function(){
        alert('이벤트 연결')
       }, false);
    }, false);
       
    </script>
</head>
<body>
        <h1 id="header">Click</h1>
</body>
</html>

실습 1

  • 국어,영어,수학을 입력 받아서 총점, 평균을 구하여 출력.
  • 유효성 체크
    1.국어,영어,수학 필수 입력
    2.숫자만 입력
    3.0~100 값만 입력
  • 출력
    국어,영어,수학,총점,평균 출력
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습</title>
<script type="text/javascript">
window.onload=function(){
	const confirm_btn = document.getElementById('confirm_btn');
	confirm_btn.onclick=function(){
		const korean = document.getElementById('korean');
		if(!check(korean,'국어')){
			return;
		}
		const english = document.getElementById('english');
		if(!check(english,'영어')){
			return;
		}
		const math = document.getElementById('math');
		if(!check(math,'수학')){
			return;
		}
		//총점 구하기
		let sum = Number(korean.value) 
		       + Number(english.value) + Number(math.value);
		//평균 구하기
		let avg = sum / 3;
		
		let msg = '국어 : ' + korean.value + '<br>';
		msg += '영어 : ' + english.value + '<br>';
		msg += '수학 : ' + math.value + '<br>';
		msg += '총점 : ' + sum + '<br>';
		msg += '평균 : ' + avg.toFixed(2);
		
		document.getElementById('result').innerHTML = msg;
	};
	
	function check(course,name){
		if(course.value.trim()==''){
			alert(name + ' 성적을 입력하세요!');
			course.value = '';//공백이 있으면 제거
			course.focus();
			return false;
		}
		
		//문자인지 숫자인지 체크
		if(isNaN(course.value)){
			alert(name + ' 성적은 숫자만 가능');
			course.value = '';
			course.focus();
			return false;
		}
		
		if(course.value < 0 || course.value > 100){
			alert('0부터 100까지만 입력 가능');
			course.value = '';
			course.focus();
			return false;
		}
		//정상적인 숫자 입력시 true 반환
		return true;
	}
	
};
</script>
</head>
<body>
<form>
	국어 <input type="text" name="korean" id="korean"><br>
	영어 <input type="text" name="english" id="english"><br>
	수학 <input type="text" name="math" id="math"><br>
	<input type="button" value="확인" id="confirm_btn">
	<div id="result"></div>
</form>
</body>
</html>

실습 2

  • CSS
<style type="text/css">
*{
	margin:0;
	padding:0;
}
h2{
	margin-top:40px;
	text-align:center;
}
table {
	margin:40px auto;
	width:600px;
}
td{
	padding-left:10px;
}
#buy{
	padding:10px 10px;
}
img{
	width:100px;
}
#preview{
	border:3px solid gray;
	margin:30px auto;
	text-align:center;
	height:50px;
}
input[type="submit"]{
	width:70px;
	height:30px;
	margin-left:500px;
	background-color:#289ca0;
	color:white;
	font-size:1.3em;
	font-weight:bold;
}
span{
	font-size:20px;
	font-weight:bold;
}
span#total{
	color:red;
}
</style>
  • JavaScript
<script type="text/javascript">
window.onload=function(){
	//가격 정보가 저장된 객체 생성
	const product = {
			c0:200000,
			c1:100000,
			c2:50000,
			c3:150000,
			c4:100000
	};
	let sum = 0;//총 구매 상품 가격
	let ship = 0;//배송비
	
	const inputs = document.querySelectorAll(
			                     'input[type="checkbox"]');
	//반복문을 이용한 이벤트 연결
	for(let i=0;i<inputs.length;i++){
		inputs[i].onclick=function(){
			if(this.checked){//체크박스 선택시
				sum += product[this.id];
			}else{//체크박스 해제시
				sum -= product[this.id];
			}
			
			//배송비 구하기
			if(sum > 0 && sum < 300000){
				ship = 5000;
			}else{
				ship = 0;
			}
			
			//구매비용과 배송비를 화면에 표시
			const spans = document.getElementsByTagName('span');
			spans[0].innerHTML = sum.toLocaleString();
			spans[1].innerHTML = ship.toLocaleString();
			spans[2].innerHTML = (sum + ship).toLocaleString();
		};
	}
};
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 구매</title>
<!-- CSS와 JS 코드 넣는 부분-->
</head>
<body>
<h2>상품 구매</h2>
<form action="order.jsp" method="post">
<table>
	<caption>구매 상품 목록</caption>
	<tr>
		<td><img src="../files/bag.jpg"></td>
		<td><img src="../files/coat.jpg"></td>
		<td><img src="../files/jeans.jpg"></td>
		<td><img src="../files/giftCard.jpg"></td>
		<td><img src="../files/shoes.jpg"></td>
	</tr>
	<tr>
		<td><input id="c0" type="checkbox" name="goods"
		                              value="bag">bag</td>
		<td><input id="c1" type="checkbox" name="goods"
		                              value="coat">coat</td>
		<td><input id="c2" type="checkbox" name="goods"
		                              value="jeans">jeans</td>
		<td><input id="c3" type="checkbox" name="goods"
		                              value="gift card">gift card</td>
		<td><input id="c4" type="checkbox" name="goods"
		                              value="shoes">shoes</td>                                                                                                                        
	</tr>
	<tr id="price">
		<td>(20만원)</td>
		<td>(10만원)</td>
		<td>( 5만원)</td>
		<td>(15만원)</td>
		<td>(10만원)</td>
	</tr>
	<tr height="100">
		<td colspan="5">*<b>30만원 미만 결제</b>시 5,000원의 배송비가 추가됩니다.</td>
	</tr>
	<tr>
		<td id="preview" colspan="5">
			총 상품가격 <span>0</span> 원 +
			총 배송비 <span>0</span> 원 = 
			총 주문금액 <span id="total">0</span></td>
	</tr>
	<tr>
		<td id="buy" colspan="5"><input type="submit" value="buy"></td>
	</tr>
</table>
</form>
</body>
</html>

실습 3

  • CSS
<style type="text/css">
div#order{
	margin:0 auto;
	width:820px;
}
table{
	border-collapse:collapse;
	border:1px solid gray;
}
td{
	height:30px;
	border:1px solid gray;
}
td.title{
	text-align:right;
	background-color:ivory;
	font-weight:bold;
	color:#ff6600;
	padding:0 10px;
}
input[type="number"]{
	text-align:right;
	width:50px;
	height:19px;
}
ul{
	list-style:none;
	padding:0 10px;
	margin:5px;
}
ul li{
	display:inline;
}
#totalMoney{
	text-align:center;
	border-style:hidden;
	font-size:15pt;
	font-weight:hold;
	color:maroon;
}
</style>
  • JavaScript
<script type="text/javascript">
window.onload=function(){
	//음식 가격 정보가 저장된 객체
	const product = {
			c0:4000,
			c1:5000,
			c2:6000
	};
	
	const foods = document.querySelectorAll(
			             'input[type="checkbox"]');
	for(let i=0;i<foods.length;i++){
		foods[i].onclick=function(){
			//이벤트가 발생한 객체를 getSum 메서드의 파라미터에 전달
			getSum(this);
		};
	}
	
	const quantity = document.querySelectorAll(
			                'input[type="number"]');
	for(let i=0;i<quantity.length;i++){
		quantity[i].onclick=function(){
			getSum(this);
		};
		quantity[i].onkeyup=function(){
			getSum(this);
		};
	}
	
	//지불할 금액을 구하는 함수
	function getSum(obj){
		if(obj.type == 'checkbox'){
			const input_num = document.getElementById('num_'+obj.id);
			if(obj.checked){//체크박스 선택시
				input_num.value = 1;
			}else{//체크박스 해제시
				input_num.value = 0;
			}
		}else{//input type="number"
			if(obj.value>=1){
				//숫자를 1이상 입력(선택)했을 때
				document.getElementById(obj.id.substr(4)).checked=true;
			}else{
				//숫자를 0으로 입력(선택)했을 때
				document.getElementById(obj.id.substr(4)).checked=false;
			}
		}
		
		
		//결과
		let sum = 0;
		//객체에 저장된 숫자를 읽어와서 연산
		for(let key in product){
			        //가격       *       수량  
			sum += product[key] * document.getElementById('num_'+key).value;
		}
		
		let totalMoney = document.getElementById('totalMoney');
		//지불 금액 표시
		totalMoney.value = sum.toLocaleString();
	}
};
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>음식 주문</title>
<!-- CSS 와 JS 코드 들어가는 곳 -->
</head>
<body>
<div id="order">
	<h2>계산서</h2>
	<form action="a.jsp" method="post">
		<table>
			<tr>
				<td class="title">식사류</td>
				<td>
					<ul>
						<li>
							<input type="checkbox"
							  id="c0" name="foodName"
							  value="짜장면" class="order-item">
							<label for="c0">짜장면(4,000원)</label>
							<input type="number" id="num_c0"
							  name="foodOrderCnt" value="0"
							  min="0" max="99"
							  class="order-item">  
						</li>
						<li>
							<input type="checkbox" id="c1"
							 name="foodName" value="짬뽕"
							 class="order-item">
							<label for="c1">짬뽕(5,000원)</label> 
							<input type="number" id="num_c1"
							 name="foodOrderCnt" value="0"
							 min="0" max="99"
							 class="order-item">
						</li>
						<li>
							<input type="checkbox" id="c2"
							  name="foodName" value="볶음밥"
							  class="order-item">
							<label for="c2">볶음밥(6,000원)</label>
							<input type="number" id="num_c2"
							 name="foodOrderCnt" value="0"
							 min="0" max="99"
							 class="order-item">  
						</li>
					</ul>
				</td>
			</tr>
			<tr>
				<td class="title">청구금액</td>
				<td>
					<input type="text" id="totalMoney"
					  name="totalMoney" size="15" value="0"
					  readonly="readonly"></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="주문">
					<input type="reset" value="취소">
				</td>
			</tr>
		</table>
	</form>
</div>
</body>
</html>
profile
Lucky Things🍀

0개의 댓글