Home > Web Front-end > JS Tutorial > body text

Detailed explanation of $(function() {}); in jQuery_jquery

WBOY
Release: 2016-05-16 15:46:10
Original
1128 people have browsed it

The code in $(document).ready() is executed after the page content is loaded. If the code is written directly into the script tag, the code inside the script tag will be executed when the page is loaded. At this time, if the code executed in your tag calls code or DOM that has not yet been loaded, an error will be reported. Of course, if you put the script tag at the end of the page, 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> 

Copy after login

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> 

Copy after login

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> 
Copy after login

Summary:

The code in $(document).ready is executed after the page content is loaded. You write it directly into the script tag. When the page is loaded, the script tag will execute the code inside. If you If the executed code 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 the effect will be similar to ready

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!