Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery ready()函数

只有完全加载DOM(文档对象模型)时,jQuery中的 ready()函数才执行代码。它是jQuery中的内置函数。它可以在加载所有图像等之前触发,但是只有在DOM准备就绪时才可以触发。仅在页面准备好执行JavaScript代码时,才执行在 $(document).ready()之间插入的代码。
我们不应该使用 ready()方法与 <body onload="">。

语法

我们可以使用 ready()通过以下两种方式起作用。
ready()函数的常用语法如下。
$(document).ready(function)
由于我们只能对当前文档使用 ready()函数,因此可以跳过选择器。我们还可以如下编写上述语法。
$(function)
以上两种方法均有效使用。第二语法可以用作第一语法的替代。从下面的代码中可以很清楚。
$(document).ready(function() {
$("p").css("color", "red");
});
上面的代码等同于下面的代码。
$(function() {
$("p").css("color", "red");
});
一些有经验的开发人员使用速记 $(),而不是使用 $(document).ready(),但是如果我们为非经验的人编写代码人,所以最好使用长格式。

参数值

ready()函数只有一个参数值定义如下。
function(): 这是强制性参数,用于指定在加载文档后执行的功能。
让我们看看使用 $(document).ready()函数的示例。

示例

在此示例中,有一些段落元素和一个按钮。在这里,我们使用 $(document).ready()函数更改给定段落的样式。
<!DOCTYpe html>
<html>
<head>
<title> jQuery ready() function </title>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css({"font-size": "30px", "color": "blue", "background": "yellow", "fontWeight": "bold"});
$("#p2").css({"fontSize": "20px", "fontWeight": "bold", "color": "red"});
$("#p3").css({"color": "blue"});
});
});
</script>
</head>
<body>
<p id = "p1"> Welcome to the lidihuo.com </p>
<p id = "p2"> This is an example of using the $(document).ready() function. </p>
<p id = "p3"> This is a third paragraph element </p>
<p> Click the following button to see the effect. </p>
<button> Click me </button>
</body>
</html>
输出:

Welcome to the lidihuo.com

This is an example of using the $(document).ready() function.

This is a third paragraph element

Click the following button to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4