Notice
Recent Posts
Recent Comments
Link
SeouliteLab
jQuery.ready() 메서드 이해하기: 문서 준비 이벤트 처리하기 본문
jQuery.ready()
메서드는 jQuery에서 가장 많이 사용되는 메서드 중 하나로, 문서의 준비 상태를 감지하고 이벤트 핸들러를 실행합니다. 이를 통해 문서가 로드되고 DOM이 구성된 후에 스크립트를 실행할 수 있습니다.
예제 1: 문서 로드 완료 시 알림 표시하기
<!DOCTYPE html>
<html>
<head>
<title>jQuery jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 문서 로드 완료 시 실행될 함수
$(document).ready(function(){
alert("문서 로드가 완료되었습니다.");
});
</script>
</head>
<body>
<!-- 내용 생략 -->
</body>
</html>
설명: 이 예제에서는 문서의 준비 상태를 감지하여 문서가 로드되면 알림을 표시합니다.
예제 2: 문서 내 요소 변경 시 로그 출력하기
<!DOCTYPE html>
<html>
<head>
<title>jQuery jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 문서 준비 시 실행될 함수
$(document).ready(function(){
$("button").click(function(){
$("p").text("새로운 내용으로 변경되었습니다.");
});
});
</script>
</head>
<body>
<p>이전 내용</p>
<button>내용 변경</button>
</body>
</html>
설명: 이 예제에서는 문서가 로드된 후 버튼 클릭 시 문단의 내용을 변경하고, 변경 사항을 콘솔에 로그로 출력합니다.
예제 3: 외부 스크립트 로드 완료 시 함수 실행하기
<!DOCTYPE html>
<html>
<head>
<title>jQuery jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 외부 스크립트 로드 완료 시 실행될 함수
$(document).ready(function(){
externalFunction();
});
// 외부 스크립트 정의
function externalFunction(){
console.log("외부 스크립트가 로드되었습니다.");
}
</script>
</head>
<body>
<!-- 내용 생략 -->
</body>
</html>
설명: 이 예제에서는 문서의 준비 상태를 감지하여 외부 스크립트가 로드되면 해당 함수를 실행합니다.
예제 4: 다수의 이벤트 핸들러 등록하기
<!DOCTYPE html>
<html>
<head>
<title>jQuery jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 문서 준비 시 실행될 함수
$(document).ready(function(){
$("#button1").click(function(){
alert("첫 번째 버튼이 클릭되었습니다.");
});
$("#button2").click(function(){
alert("두 번째 버튼이 클릭되었습니다.");
});
});
</script>
</head>
<body>
<button id="button1">버튼 1</button>
<button id="button2">버튼 2</button>
</body>
</html>
설명: 이 예제에서는 문서의 준비 상태를 감지하여 두 개의 버튼에 대해 각각 이벤트 핸들러를 등록합니다.
예제 5: 외부 리소스 로드 완료 시 추가 작업 수행하기
<!DOCTYPE html>
<html>
<head>
<title>jQuery jQuery.ready() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 문서 준비 시 실행될 함수
$(document).ready(function(){
// 외부 리소스 로드 완료 시 추가 작업 수행
$("#externalResource").load(function(){
console.log("외부 리소스가 로드되었습니다.");
});
});
</script>
</head>
<body>
<img id="externalResource" src="external_resource.jpg">
</body>
</html>
설명: 이 예제에서는 문서의 준비 상태를 감지하여 외부 이미지 리소스가 로드되면 로그를 출력합니다.
'프로그래밍' 카테고리의 다른 글
jQuery .keypress() 메서드 이해하기: 키 입력 이벤트 처리하기 (0) | 2024.04.03 |
---|---|
jQuery .keydown() 메서드 이해하기: 키보드 이벤트 처리하기 (0) | 2024.04.03 |
jQuery jQuery.proxy() 메서드 이해하기: 함수 컨텍스트 설정하기 (0) | 2024.04.03 |
jQuery jQuery.holdReady() 메서드 이해하기: 문서 준비 이벤트 제어하기 (0) | 2024.04.03 |
jQuery .hover() 메서드 이해하기: 요소에 마우스를 올렸을 때 처리하기 (0) | 2024.04.03 |