📅  最后修改于: 2023-12-03 15:32:09.525000             🧑  作者: Mango
jQuery on ready is a popular method in jQuery that allows developers to execute a code block when the DOM (Document Object Model) is fully loaded. In simple terms, it ensures that the HTML document is ready to manipulate before running a script.
The syntax for jQuery on ready is as follows:
$(document).ready(function(){
// code block to be executed
});
It can also be written in short by using the $()
method:
$(function(){
// code block to be executed
});
Both of the above methods are equivalent and will execute the code block once the DOM is fully loaded.
The use of jQuery on ready is important because it ensures that scripts don't run before the HTML document is fully loaded. This can prevent errors and unexpected results from occurring in the application.
In the following example, we use jQuery on ready to show an alert box when the page is fully loaded:
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
alert("Page is fully loaded");
});
</script>
</body>
The following example shows how to use jQuery on ready in a function that can be called later:
function doSomething() {
// code to be executed when the DOM is fully loaded
}
$(document).ready(doSomething);
jQuery on ready allows you to execute multiple functions when the DOM is fully loaded. The following example shows how to use multiple functions with jQuery on ready:
$(document).ready(function() {
function func1() {
console.log("Function 1");
}
function func2() {
console.log("Function 2");
}
func1();
func2();
});
In this example, we have defined two functions (func1
and func2
), and both of them are executed when the DOM is fully loaded.
jQuery on ready is an important method in jQuery that ensures scripts run only after the HTML document is fully loaded. It can also be used to execute multiple functions when the DOM is loaded.