본문 바로가기
JQuery

jQuery - 이벤트 핸들링

by Status Code 2024. 1. 28.

jQuery - 이벤트 핸들링

jQuery는 웹 페이지의 이벤트를 처리하는 데 강력하고 유연한 방법을 제공합니다. 이번 포스팅에서는 jQuery를 사용한 이벤트 핸들링의 기본적인 방법들을 알아보겠습니다.

기본 이벤트 핸들링

jQuery를 사용하면 다양한 사용자 이벤트를 쉽게 처리할 수 있습니다.

예제: 클릭 이벤트

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<button id="clickButton">클릭하세요</button>

<script>
$(document).ready(function(){
    $("#clickButton").click(function(){
        alert("버튼이 클릭되었습니다!");
    });
});
</script>

</body>
</html>

이 예제에서는 버튼이 클릭될 때 알림 메시지를 표시합니다.

마우스 이벤트

마우스와 관련된 이벤트를 처리할 수 있습니다.

예제: 마우스 오버 및 아웃 이벤트

$(document).ready(function(){
    $("#hoverDiv").mouseover(function(){
        $(this).css("background-color", "yellow");
    }).mouseout(function(){
        $(this).css("background-color", "lightgray");
    });
});

이 예제에서는 마우스가 요소 위에 올라가거나 벗어날 때 배경색을 변경합니다.

키보드 이벤트

키보드 입력과 관련된 이벤트를 처리할 수 있습니다.

예제: 키보드 키 누름 이벤트

$(document).ready(function(){
    $("#inputField").keypress(function(){
        $("#keyPressResult").text("키가 눌렸습니다: " + event.which);
    });
});

이 예제에서는 키보드 키를 누를 때 해당 키의 코드를 표시합니다.

Form 이벤트

폼 관련 이벤트를 처리할 수 있습니다.

예제: 폼 제출 이벤트 (submit)

$(document).ready(function(){
    $("#form").submit(function(e){
        e.preventDefault();
        alert("폼이 제출되었습니다!");
    });
});

이 예제에서는 폼 제출 이벤트를 처리하고 기본 제출 동작을 방지합니다.

예제: 포커스 및 블러 이벤트 (focus, blur)

$(document).ready(function(){
    $("#inputField").focus(function(){
        $(this).css("background-color", "lightblue");
    }).blur(function(){
        $(this).css("background-color", "white");
    });
});

이 예제에서는 입력 필드가 포커스를 받거나 잃었을 때 배경색을 변경합니다.

예제: 변경 이벤트 (change)

$(document).ready(function(){
    $("#selectBox").change(function(){
        alert("선택된 옵션: " + $(this).val());
    });
});

이 예제에서는 선택 상자의 값이 변경될 때 이벤트를 처리합니다.

이벤트 위임

이벤트 위임을 사용하여 여러 요소에 대해 이벤트를 처리할 수 있습니다.

예제: 이벤트 위임

$(document).ready(function(){
    $("#parentDiv").on("click", "button", function(){
        alert("버튼 클릭됨!");
    });
});

이 예제에서는 부모 요소에서 버튼 클릭 이벤트를 처리합니다.

이벤트 제거

이벤트 핸들러를 제거할 수도 있습니다.

예제: 이벤트 제거

$(document).ready(function(){
    $("#removeButton").click(function(){
        $("#clickButton").off("click");
    });
});

이 예제에서는 클릭 이벤트 핸들러를 제거합니다.

이 포스팅에서는 jQuery를 사용한 이벤트 핸들링의 기본적인 방법들을 살펴보았습니다. 이벤트 핸들링은 웹 페이지의 상호작용성을 높이는 중요한 요소이며, jQuery를 사용하면 이를 간편하고 효과적으로 수행할 수 있습니다.

'JQuery' 카테고리의 다른 글

JQuery - 유틸리티 함수  (2) 2024.01.28
jQuery - AJAX 통신  (0) 2024.01.28
JQuery - 애니메이션 및 효과  (0) 2024.01.28
jQuery - DOM 조작  (0) 2024.01.27
jQuery - 기본 사용법 및 개념  (0) 2024.01.27

댓글