프로그램
jQuery의 click() 이벤트를 실용적으로 활용하는 기본적인 예제
다온다올과함께
2024. 11. 18. 11:52

jQuery의 click() 이벤트 함수는 사용자가 HTML 요소를 클릭할 때 특정 작업을 수행하도록 JavaScript 코드를 실행하는 데 사용됩니다. 아래는 가장 일반적으로 사용되는 click() 이벤트 함수 예제 입니다.
1. 버튼 클릭 시 텍스트 변경
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery click() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#myButton").click(function() {
$("#myText").text("버튼이 클릭되었습니다!");
});
});
</script>
</head>
<body>
<button id="myButton">클릭하세요</button>
<p id="myText">이곳의 텍스트가 변경됩니다.</p>
</body>
</html>
2. 리스트 항목 추가하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Add Item</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#addItem").click(function() {
$("#itemList").append("<li>새 항목</li>");
});
});
</script>
</head>
<body>
<button id="addItem">리스트 항목 추가</button>
<ul id="itemList">
<li>기존 항목 1</li>
<li>기존 항목 2</li>
</ul>
</body>
</html>
3. 토글 버튼으로 요소 보이기/숨기기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Toggle Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#toggleButton").click(function() {
$("#toggleText").toggle();
});
});
</script>
</head>
<body>
<button id="toggleButton">토글</button>
<p id="toggleText" style="display: none;">이 텍스트는 토글됩니다.</p>
</body>
</html>
4. 특정 클래스의 모든 버튼에 이벤트 적용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Multiple Buttons</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$(".clickButton").click(function() {
alert($(this).text() + " 버튼이 클릭되었습니다!");
});
});
</script>
</head>
<body>
<button class="clickButton">버튼 1</button>
<button class="clickButton">버튼 2</button>
<button class="clickButton">버튼 3</button>
</body>
</html>
이 예제들은 jQuery의 click() 이벤트를 실용적으로 활용하는 데 기본적인 시작점이 될 것입니다. 원하는 대로 확장하거나 변경할 수 있습니다.
#jquery #html #javascript #event #function #click() #click함수
반응형