HOWTO · jQuery
페이지 로드 후 jQuery 실행
이 튜토리얼은 페이지 로드 후 jQuery를 실행하는 방법을 보여줍니다.
이 페이지의 내용
이 튜토리얼은 페이지 로드 후 jQuery를 실행하는 방법을 보여줍니다.
페이지를 로드한 후 jQuery 코드를 실행하는 것은 두 가지 방법을 사용하여 수행할 수 있습니다. 하나는 ready() 메서드이고 다른 하나는 로드 이벤트가 있는 on() 메서드입니다.
ready()를 사용하여 페이지 로드 후 jQuery 실행
jQuery의 ready() 메서드는 완전히 로드된 DOM 이후에만 jQuery 코드를 실행합니다. ready()는 DOM이 완전히 로드된 후 jQuery 코드를 호출하는 내장 jQuery 메서드입니다. 이미지 및 비디오와 같은 무거운 파일이 완전히 로드될 때까지 기다리지 않습니다.
ready() 메서드는 <body onload = ""> 이벤트와 함께 사용되지 않습니다. 이 방법의 구문은 다음과 같습니다.
$(document).ready(function)
ready() 메서드는 현재 문서에만 사용할 수 있습니다. 여기서 함수는 페이지가 로드된 후 실행하려는 jQuery 코드입니다. 이 방법의 예를 시도해 보겠습니다.
<!DOCTYPE html>
<html>
<head>
<title> jQuery ready() function </title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#h1").css({"font-size": "80px", "color": "lightblue", "background": "darkblue", "fontWeight": "bold"});
$("#h2").css({"fontSize": "50px", "fontWeight": "bold", "color": "lightblue"});
$("#para").css({"color": "blue"});
});
});
</script>
</head>
<body>
<h1 id = "h1"> Delftstack.com </h1>
<h2 id = "h2"> Example of $(document).ready() from Delftstack. </h2>
<p id = "para"> </p>
<p> This is an example for ready() method in jQuery </p>
<button> After Page Load </button>
</body>
</html>
보시다시피 여기에서 클릭 이벤트를 사용합니다. 이 클릭은 DOM이 로드된 후에만 작동합니다.
출력을 참조하십시오.
on()을 사용하여 페이지 로드 후 jQuery 실행
on() 메서드는 페이지를 로드한 후 jQuery 코드를 실행하기 위해 load 이벤트와 함께 사용할 수 있습니다. load가 포함된 on() 메서드는 이미지 및 비디오와 같은 무거운 개체를 포함하는 전체 페이지가 로드될 때 작동합니다.
on() 메서드는 다양한 작업을 위한 내장 jQuery 메서드입니다. 이 방법의 구문은 다음과 같습니다.
$(selector).on(event, childSelector, data, function, map)
어디:
event는 필수 매개변수입니다. 우리의 경우에는로드가 됩니다.childSelector는 이벤트가 첨부될 하위 요소를 지정하기 위한 선택적 매개변수입니다.data는 이벤트가 트리거될 때 전달될 데이터에 사용되는 선택적 매개변수이기도 합니다.function은 이벤트가 트리거될 때 호출되는 선택적 매개변수이기도 합니다.지도는 이벤트 지도입니다.
이제 on() 메서드를 사용하여 페이지가 로드된 후 jQuery 코드를 실행하는 예제를 시도해 보겠습니다.
<!DOCTYPE html>
<html>
<head>
<title>jQuery on(load) method</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<h1 id = "h1"> Delftstack.com </h1>
<h2 id = "h2"> Example of $(document).ready() from Delftstack. </h2>
<p id = "para"> </p>
<p> This is an example for ready() method in jQuery </p>
<button> After Page Load </button>
<script type="text/javascript">
$(window).on('load', DemoFunction());
function DemoFunction() {
$("#h1").css({"font-size": "80px", "color": "lightblue", "background": "darkblue", "fontWeight": "bold"});
$("#h2").css({"fontSize": "50px", "fontWeight": "bold", "color": "lightblue"});
$("#para").css({"color": "blue"});
}
</script>
</body>
</html>
위의 코드는 페이지가 완전히 로드될 때 CSS를 변경합니다. 출력을 참조하십시오.