염몽 개발일지

학교에서 간단하게 이벤트를 배웠다.

 

이벤트란?

문서 객체에 이벤트를 연결하는 방법이다.

 

DOM Level 버전에 따라 구분된다.

DOM Level 0 : 인라인이벤트모델,고전이벤트모델

DOM Level 2 : 마이크로소프트 인터넷 익스플로러 이벤트 모델, 표준 이벤트 모델

(Level2는 요즘 잘 쓰지 않는다고 한다.)

 

대표적으로 window객체의 onload 는 모든 document가 로드되고, 발동되는 메소드이다.

on으로 시작되는 이벤트는 무수히 많다.

 

마우스 이벤트, 키보드 이벤트, 기타 이벤트 등등..

 

보통 고전 이벤트 모델을 주로 사용한다.

 

1. 인라인 이벤트 모델

HTML 태그 내부에서 이벤트를 연결하는 방법

가장 기본적인 이벤트 연결방식

 

2. 고전 이벤트 모델

 


 

이제 학교에서 내준 과제를 한번 해보자.

이번 과제는, input 필드에 이름과 전화번호를 적고 회원가입 버튼을 누르면 object 형태로 저장이되고,

배열로 저장시켜 출력하는 과제이다.

 

현재까지 배운 실력으로, 최대한 예외처리를 해보려고 노력을 많이 해보았던 것 같다.

 

 

결과 및 코드:

 

<html />
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>2155106 염성현</title> <script> //div1 script //회원 정보 배열 var data_array = []; //이름과 연락처 값을 저장하기 위한 변수 var name = ''; var phone = ''; /* 예외 처리 목록: 이름 필드가 비어있는 경우 연락처 필드가 비어있는 경우 이름 필드에 숫자가 포함된 경우 연락처 필드가 숫자 11자리가 아닌 경우 이미 등록된 번호가 입력된 경우 등록된 회원이 없는데, 출력 버튼 누를 경우 */ //회원가입 버튼 함수 function submit_chk(myForm) { if(isValidCheck()) { var data = {}; data['name'] = name; data['phone'] = phone; // 중복 체크 for (var i = 0; i < data_array.length; i++) { if (data_array[i]['phone'] === phone) { alert("이미 등록된 번호입니다."); document.querySelector('#user_tel').value = null; document.f1.user_tel.focus(); return false; } } alert("회원가입이 완료되었습니다."); //이름과 연락처 필드 초기화 document.querySelector('#user_name').value = null; document.querySelector('#user_tel').value = null; document.f1.user_name.focus(); data_array.push(data); } return false; } //가입 취소 버튼 함수 function reset_chk(myForm) { alert("가입이 취소되었습니다."); //이름과 연락처 필드 초기화 document.querySelector('#user_name').value = null; document.querySelector('#user_tel').value = null; document.f1.user_name.focus(); return false; } //회원 가입해도 되는지 체크 function isValidCheck() { const nameInput = document.querySelector('#user_name'); const phoneInput = document.querySelector('#user_tel'); if (nameInput !== null) { name = nameInput.value.trim(); } if (phoneInput !== null) { phone = phoneInput.value.trim(); } if (name === '') { alert("이름을 먼저 입력해주세요."); document.f1.user_name.focus(); return false; } else if (phone === '') { alert("연락처를 먼저 입력해주세요."); document.f1.user_tel.focus(); return false; } else if (hasNumber(name)) { alert("이름에는 숫자를 넣을 수 없습니다."); nameInput.value = null; document.f1.user_name.focus(); return false; } else if (isNaN(phone) || phone.length !== 11) { alert("올바른 연락처를 입력해주세요. (숫자11자리)"); phoneInput.value = null; document.f1.user_tel.focus(); return false; } return true; } //이름에 숫자가 있는지 확인 function hasNumber(str) { for (var i = 0; i < str.length; i++) { if (!isNaN(str.charAt(i))) { return true; } } return false; } </script> <script> //div 2,3 scripts //출력: data_array //예외 처리: 등록된 회원 정보가 없으면 알람 function resultBtn() { if(data_array.length === 0) { alert("등록된 회원 정보가 없습니다."); return; } console.log(data_array); const result = document.querySelector('#input_text'); result.innerHTML = null; //회원 정보 출력 let num = 1; data_array.forEach((item) => { result.innerHTML += `<b>${num++}번째 회원</b><br> <li>이름: ${item.name}</li> <li>연락처: ${item.phone}</li><hr color="green" noshade/>`; }); alert("모든 회원 정보가 출력됩니다."); } function clearBtn() { if(data_array.length === 0) { alert("등록된 회원 정보가 없습니다."); return; } const result = document.querySelector('#input_text'); result.innerHTML = null; alert("출력이 초기화 됩니다."); } </script> </head> <body onload = "document.f1.user_name.focus();"> <div> <form action="#" method="POST" name = "f1" onsubmit="return submit_chk(this);" onreset="return reset_chk(this);"> <fieldset> <p> <label for="user_name"> 이름 </label> <input type="text" name="user_name" id="user_name"/> </p> <p> <label for="user_name"> 연락처 </label> <input type="text" name="user_tel" id="user_tel"/> </p> <p> <input type="submit" value="회원가입"/> <input type="reset" value="가입취소"/> </p> </fieldset> </form> </div> <div> <fieldset> <button type="button" id="resultBtn" onclick="resultBtn();">출력 버튼</button> <button type="button" id="clearBtn" onclick="clearBtn();">출력 초기화 버튼</button> </fieldset> </div> <div> <ul> <text id = "input_text"></text> </ul> </div> </body> </html>

 

'Study > JavaScript' 카테고리의 다른 글

JavaScript. 입출력, 변수와 자료형 연산자  (0) 2023.04.13
profile

염몽 개발일지

@염몽이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!