jQuery ready()方法
jQuery ready()方法有助于加载整个页面,然后执行其余代码。这个方法指定了当DOM被完全加载时要执行的函数。
语法:
$(document).ready(function)
参数:该方法接受一个参数function,这是必须的。它被用来指定文档加载后要运行的函数。
返回值:该方法在执行ready()方法后返回文档。
例子1:这个例子说明了jQuery的ready()方法。
<!DOCTYpe html>
<html>
<head>
<title>The ready Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function () {
("button").click(function () {
("p").css("color", "green");
("p").css("font-size", "40px");
$("p").css("font-weight", "bold")
});
});
</script>
<style>
div {
text-align: center;
width: 60%;
min-height: 100px;
padding: 10px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>Welcome to</p>
<p>GeeksforGeeks!</p>
<!-- click on this button -->
<button>Click Here!</button>
</div>
</body>
</html>
输出:
实例2:在这个例子中,我们将在ready()方法中对文本进行动画处理。
<!DOCTYpe html>
<html>
<head>
<title>The ready Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function () {
("button").click(function () {
$("p").animate({ fontSize: "+=14px"});
});
});
</script>
<style>
div {
text-align: center;
width: 60%;
min-height: 100px;
padding: 10px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>Welcome to</p>
<p>GeeksforGeeks!</p>
<!-- click on this button -->
<button>Click Here!</button>
</div>
</body>
</html>
输出: