SeouliteLab

jQuery의 jQuery.ready() 메서드: 문서가 준비되면 실행되는 이벤트 핸들러 본문

프로그래밍

jQuery의 jQuery.ready() 메서드: 문서가 준비되면 실행되는 이벤트 핸들러

Seoulite Lab 2024. 3. 30. 01:00

jQuery의 jQuery.ready() 메서드는 문서 객체 모델(DOM)이 완전히 로드되고 초기화된 후에 실행할 코드를 정의하는 데 사용됩니다. 이 메서드를 사용하면 HTML 문서의 모든 요소가 로드된 후에 JavaScript 코드를 실행할 수 있어서 안전하고 일관된 방식으로 코드를 작성할 수 있습니다.

예제 1: jQuery.ready()를 사용하여 문서가 준비되면 메시지 출력하기

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// jQuery.ready()를 사용하여 문서가 준비되면 실행될 코드 정의
jQuery(document).ready(function(){
  alert("문서가 준비되었습니다!");
});
</script>
</head>
<body>
<!-- HTML 내용 -->
</body>
</html>
<!-- 출력 결과 -->
<!-- 문서가 준비되면 경고창이 표시됨 -->

예제 2: jQuery.ready()를 사용하여 다양한 동작 수행하기

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// jQuery.ready()를 사용하여 문서가 준비되면 실행될 코드 정의
jQuery(document).ready(function(){
  // 버튼 클릭 시 메시지 변경
  jQuery("button").click(function(){
    jQuery("p").text("버튼이 클릭되었습니다!");
  });
  // 문서가 준비되면 로그에 메시지 출력
  console.log("문서가 준비되었습니다!");
});
</script>
</head>
<body>
<button>클릭하세요</button>
<p>여기에 메시지가 표시됩니다.</p>
</body>
</html>
<!-- 출력 결과 -->
<!-- 버튼 클릭 시 메시지 변경 -->
<!-- 콘솔에 "문서가 준비되었습니다!" 메시지 출력 -->

예제 3: jQuery()를 사용하여 jQuery.ready() 축약형 사용하기

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery.ready() 축약형 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// jQuery()를 사용하여 문서가 준비되면 실행될 코드 정의
jQuery(function(){
  alert("문서가 준비되었습니다!");
});
</script>
</head>
<body>
<!-- HTML 내용 -->
</body>
</html>
<!-- 출력 결과 -->
<!-- 문서가 준비되면 경고창이 표시됨 -->