[JavaScript] 4. Event

김미숙's avatar
Apr 03, 2025
[JavaScript] 4. Event
notion image

Event 종류

notion image
 

ex05/test01.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>이벤트</h1> <hr /> <button onclick="m1()">클릭</button> <div onclick="m2()">클릭2</div> <script> function m1() { // window 객체는 생략가능함 window.alert("m1 호출됨"); } function m2() { // window 객체는 생략가능함 window.alert("m2 호출됨"); } </script> </body> </html>
notion image
notion image

ex05/test02.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>이벤트 리스너</h1> <hr /> <button id="btn1">클릭</button> <script> let btn1 = document.querySelector("#btn1"); btn1.addEventListener("click", (e) => { console.log(e); alert("btn1 호출됨"); }); </script> </body> </html>
notion image

ex05/test03.html

<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>이벤트 예제</title> </head> <body> <h1>이벤트 종류</h1> <hr /> <!-- click --> <button id="btn1">클릭</button> <!-- dblclick --> <button id="btn2">더블 클릭</button> <!-- keyup --> <input type="text" id="textInput" placeholder="키보드 입력해 보세요" /> <!-- change --> <select id="selectBox"> <option value="">선택하세요</option> <option value="apple">🍎 사과</option> <option value="banana">🍌 바나나</option> <option value="grape">🍇 포도</option> </select> <script> // click let btn1 = document.querySelector("#btn1"); btn1.addEventListener("click", (e) => { console.log("click 이벤트:", e); alert("btn1 클릭됨"); }); // dblclick let btn2 = document.querySelector("#btn2"); btn2.addEventListener("dblclick", () => { alert("btn2 더블 클릭됨"); }); // keyup let value = ""; let input = document.querySelector("#textInput"); input.addEventListener("keyup", (e) => { console.log("입력된 키:", e.key); value += e.key; console.log(value); if (value.length > 4) { alert("글자수 5"); } }); // change let select = document.querySelector("#selectBox"); select.addEventListener("change", (e) => { console.log(e); alert("선택한 값: " + e.target.value); }); </script> </body> </html>
notion image
notion image
notion image
notion image

ex05/test04.html

onsubmit

<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .hidden-box { display: none; } .red-text { font-size: 10px; color: red; } </style> </head> <body> <h1>폼 이벤트</h1> <hr /> <form action="/join" onsubmit="return valid()"> <input type="text" id="password" /><br /> <input type="text" id="password-check" /><br /> <div id="pw-same" class="hidden-box red-text">패스워드가 동일합니다</div> <div id="pw-not-same" class="hidden-box red-text"> 패스워드가 동일하지 않습니다 </div> <button type="submit">회원가입</button> </form> <script> let pw = document.querySelector("#password"); let pwCheck = document.querySelector("#password-check"); function valid() { if (pw.value == pwCheck.value) { return true; } else { alert("패스워드가 동일해야 합니다"); return false; } } pw.addEventListener("keyup", (e) => { if (pw.value == pwCheck.value) { pw.readOnly = true; document.querySelector("#pw-same").classList.remove("hidden-box"); document.querySelector("#pw-not-same").classList.add("hidden-box"); } else { pw.readOnly = false; document.querySelector("#pw-same").classList.add("hidden-box"); document.querySelector("#pw-not-same").classList.remove("hidden-box"); } }); pwCheck.addEventListener("keyup", (e) => { if (pw.value == pwCheck.value) { pw.readOnly = true; document.querySelector("#pw-same").classList.remove("hidden-box"); document.querySelector("#pw-not-same").classList.add("hidden-box"); } else { pw.readOnly = false; document.querySelector("#pw-same").classList.add("hidden-box"); document.querySelector("#pw-not-same").classList.remove("hidden-box"); } }); </script> </body> </html>
notion image
notion image

ex05/test05.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <style> .box { border: 1px solid black; padding: 10px; } </style> </head> <body> <h1>숨기기</h1> <button onclick="hideDisplay()">display로 숨기기</button> <button onclick="hideVisible()">visible로 숨기기</button> <button onclick="empty()">박스 내부 날리기</button> <div class="box" id="outerBox"> <div class="box" id="innerBox1">내부박스1</div> <div class="box" id="innerBox2">내부박스2</div> </div> <script> function hideDisplay() { let el = document.querySelector("#innerBox1"); el.style.display = "none"; } function hideVisible() { let el = document.querySelector("#innerBox2"); el.style.visibility = "hidden"; } function empty() { let el = document.querySelector("#outerBox"); //el.innerHTML = ""; //console.log(el.children); let cs = el.children; //cs[0].style.display = "none"; Array.from(cs).forEach((element) => { element.style.display = "none"; }); } </script> </body> </html>
notion image
notion image
notion image
notion image
notion image
notion image

ex05/test.js

Array.from() 과 .forEach()

‼️

1. Array.from()

  • Array.from()은 유사 배열 객체(array-like object)나 이터러블 객체를 실제 배열로 변환하는 메서드

2. .forEach()

  • forEach()는 배열의 각 요소를 반복(iterate)하면서 콜백 함수를 실행하는 메서드

📌 유사 배열 객체 (Array-like Object)란?
  • 유사 배열 객체(Array-like Object)란, 배열처럼 length 속성을 가지고 있고, 인덱스를 통해 요소에 접근할 수 있지만, 배열의 메서드(map(), forEach() 등)는 직접 사용할 수 없는 객체
✅ 유사 배열 객체의 특징
  1. length 속성을 가지고 있다.
  1. 인덱스(숫자 키)로 요소에 접근할 수 있다.
  1. 배열이 아니므로 push(), pop(), forEach(), map() 같은 배열 메서드를 직접 사용할 수 없다.
  1. Array.from() 또는 [...](스프레드 연산자)를 사용하여 배열로 변환할 수 있다.

📌 이터러블 객체(Iterable Object)란?
이터러블(Iterable) 객체for...of 루프를 사용할 수 있는 객체
즉, 내부에서 반복(iteration)이 가능한 객체로, Symbol.iterator 메서드를 가지고 있다.
이터러블 객체의 특징
  1. Symbol.iterator 메서드를 가지고 있다.
  1. for...of 루프를 사용할 수 있다.
  1. 스프레드 연산자 (...), Array.from() 등을 사용하여 배열로 변환할 수 있다.
let list = { 0: "a", 1: "b", 2: "c", length: 3, }; Array.from(list).forEach((e) => { console.log(e); });
notion image

ex05/test06.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <style> .box { border: 1px solid black; padding: 10px; } #innerBox1 { display: none; } #innerBox2 { visibility: hidden; } </style> </head> <body> <h1>나타내기</h1> <button onclick="showByDisplay()">display로 나타내기</button> <button onclick="showByVisible()">visible로 나타내기</button> <div class="box" id="outerBox"> <div class="box" id="innerBox1">내부박스1</div> <div class="box" id="innerBox2">내부박스2</div> </div> <script> function showByDisplay() { let el = document.querySelector("#innerBox1"); el.style.display = "block"; } function showByVisible() { let el = document.querySelector("#innerBox2"); el.style.visibility = "visible"; } </script> </body> </html>
notion image
notion image
notion image
notion image

ex05/test07.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <style> .box { border: 1px solid black; padding: 10px; } </style> </head> <body> <h1>추가하기</h1> <button onclick="addAppend()">append로 추가하기</button> <button onclick="addPrepend()">prepend로 추가하기</button> <button onclick="addBefore()">before로 추가하기</button> <button onclick="addAfter()">after로 추가하기</button> <div class="box" id="outerBox"></div> <script> function del(e) { console.log(e.target); e.target.style.display = "none"; } function addAppend() { let newEl = document.createElement("div"); newEl.setAttribute("class", "box"); newEl.setAttribute("onclick", "del(event)"); newEl.innerHTML = "내부박스1"; let el = document.querySelector("#outerBox"); el.append(newEl); } function addPrepend() { let newEl = document.createElement("div"); newEl.setAttribute("class", "box"); newEl.setAttribute("id", "innerBox2"); newEl.innerHTML = "내부박스2"; let el = document.querySelector("#outerBox"); el.prepend(newEl); } function addBefore() { let newEl = document.createElement("div"); newEl.setAttribute("class", "box"); newEl.setAttribute("id", "innerBox3"); newEl.innerHTML = "내부박스3"; let el = document.querySelector("#outerBox"); el.before(newEl); } function addAfter() { let newEl = document.createElement("div"); newEl.setAttribute("class", "box"); newEl.setAttribute("id", "innerBox4"); newEl.innerHTML = "내부박스4"; let el = document.querySelector("#outerBox"); el.after(newEl); } </script> </body> </html>
notion image

ex05/test08.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <style> .box { border: 1px solid black; padding: 10px; } </style> </head> <body> <h1>삭제하기</h1> <button onclick="del()">remove로 삭제하기</button> <div class="box" id="outerBox"> <div class="box" id="innerBox1">내부박스1</div> </div> <script> function del() { let el = document.querySelector("#innerBox1"); el.remove(); } </script> </body> </html>
notion image
notion image

ex05/test09.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <style> .box { display: grid; grid-template-columns: 1fr 1fr 1fr; border: 1px solid black; padding: 10px; } .card { border: 1px solid lightgray; box-shadow: 0 4px 4px 0 grey; padding: 10px; margin: 5px; border-radius: 5px; } </style> </head> <body> <h1>반복문으로 리스트 만들기</h1> <button onclick="render()">render</button> <div class="box" id="outerBox"></div> <script> let id = 1; function render() { let el = document.querySelector("#outerBox"); el.append(makeCard(id)); id++; } function makeCard(id) { let card = document.createElement("div"); card.setAttribute("class", "card"); card.setAttribute("id", "card-" + id); card.innerHTML = ` <h3>제목${id} 입니다</h3> <p>내용${id} 입니다</p> <button onclick="del(${id})">삭제</button> `; return card; } function del(id) { let el = document.querySelector("#card-" + id); el.remove(); } </script> </body> </html>
notion image
notion image
notion image
notion image
Share article

parangdajavous