오늘은 JavaScript 이벤트 처리 방식에 대해 학습했다. 웹에서 사용자와 상호작용하는 핵심인 이벤트 시스템은 크게 세 가지 모델로 나뉜다: 인라인 이벤트 모델, 고전 이벤트 모델, 그리고 표준 이벤트 모델(addEventListener).
HTML 태그 속성으로 이벤트를 직접 작성하는 방식이다.
<button onclick="check1(this)" style="background-color: yellow;">
인라인 이벤트 모델 확인
</button>
JavaScript:
function check1(btn){
const bgColor = btn.style.backgroundColor;
btn.style.backgroundColor = bgColor === "yellow" ? "pink" : "yellow";
}
✅ 장점:
❌ 단점:
DOM 요소의 속성으로 이벤트 핸들러를 등록하는 방식.
<button id="test1-1">고전 이벤트 모델 확인</button>
<button id="test1-2">고전 이벤트 모델 제거</button>
<button id="test1-3">고전 이벤트 모델 단점</button>
const test1a = document.querySelector("#test1-1");
test1a.onclick = function(){ alert("버튼 클릭됨"); };
document.querySelector("#test1-2").onclick = function(){
test1a.onclick = null;
alert("이벤트 제거됨");
};
const test1c = document.querySelector("#test1-3");
test1c.onclick = function(){ test1c.style.backgroundColor = "red"; };
test1c.onclick = function(){ test1c.style.color = "white"; }; // 위 이벤트 덮어씀
✅ 장점:
❌ 단점:
W3C 표준 방식으로 이벤트를 등록. 다수 이벤트 등록이 가능하며 유연하고 강력하다.
const test2 = document.querySelector("#test2");
let count = 0;
test2.addEventListener("click", function() {
let curr = this.style.opacity || 1;
this.style.opacity = curr - 0.1 <= 0 ? 1 : curr - 0.1;
});
test2.addEventListener("click", function() {
count++;
this.innerText = count;
});
const input3 = document.querySelector("#input3");
const box3 = document.querySelector("#box3");
input3.addEventListener("keyup", function(e) {
if(e.key === "Enter") {
box3.style.backgroundColor = input3.value;
}
});
box3.addEventListener("click", function(e) {
alert(`배경색: ${e.target.style.backgroundColor}`);
});
✅ 장점:
❌ 단점: