This time I will bring you a use case of $(function() {}) in jQuery. What are the precautions for using $(function() {}) in jQuery? The following is a practical case. Let’s take a look.
$(function() {}); is the abbreviation of $(document).ready(function(){ }). When I first came into contact with it, I also said $(document).ready(function(){ } ) This function is used to replace window.onload in the page; but today I found that this does not seem to be the case! I discovered it while doing a page loading effect! The code in
$(document).ready() is executed after the page content is loaded. If the code is written directly into the script tag, the script tag will be executed when the page is loaded. code. At this time, if the code executed in your tag calls the code or DOM that has not been loaded yet, an error will be reported. Of course, if you put the script tag at the end of the page, then there will be no problem. At this time, it is the same as ready. The effect is the same.
$(document).ready(function(){}) can be abbreviated as $(function(){});
After clicking on the paragraph, this paragraph will be hidden:
<html> <head> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> </body> </html>
If you remove $(document).ready(function() {});, the paragraph cannot be hidden:
<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $("p").click(function(){ $(this).hide(); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> </body> </html>
But if you put the script at the end of the page, the hiding effect can be restored:
<html> <head> </head> <body> <p>If you click on me, I will disappear.</p> </body> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> $("p").click(function(){ $(this).hide(); }); </script> </html>
Summary: The code in
$(document).ready is executed after the page content is loaded. You write it directly into the script tag, and the script tag will be executed when the page is loaded. If the code executed in your tag calls code or DOM that has not been loaded yet, an error will be reported.
Of course, if you put the script tag at the end of the page, then there will be no problem and ready. Similar effect
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
What are the precautions for jQuery version upgrade
Use of $. and $(). in jQuery Detailed explanation
The above is the detailed content of Use cases of $(function() {}) in jQuery. For more information, please follow other related articles on the PHP Chinese website!