$(function() {....}) in JavaScript is a classic usage in jQuery, which is equivalent to $(document).ready(function() {.... }), means that a function is executed only after the page is loaded. If the DOM is to be manipulated in the function, it will be safer to execute it after the page is loaded, so this writing method is very common when using jQuery.
$(document).ready() The code in 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. The code inside is executed. 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. The effect is the same as ready.
$(document).ready(function(){}) can be abbreviated as $(function(){});
After clicking on the paragraph, this paragraph is 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 $(document).ready(function() {}); is removed, 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 hidden 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>
What are the functions and usages of (function(){})() in javascript
It has nothing to do with the person
(function(){})() represents the immediate execution of an anonymous method
Generally used to isolate from the outside world, create a closure-like environment, create a scope chain, and avoid variable conflicts
(function(){ var a; .......... })()
This article mainly introduces the differences between writing and not writing $(function() {}); in JavaScript. I hope it will be helpful to everyone.