Home > Web Front-end > JS Tutorial > How to write jquery and the difference between executing JS after the page is loaded_jquery

How to write jquery and the difference between executing JS after the page is loaded_jquery

WBOY
Release: 2016-05-16 16:58:42
Original
1345 people have browsed it

1. $(function(){
 $("#a").click(function(){
   //adding your code here
 });
});
2. $(document).ready(function(){
 $("#a").click(function(){
   //adding your code here  
 });
});
3. window.onload = function(){
 $("#a").click(function(){
   //adding your code here
 });
}
The html code is click, and the page needs to reference the js file of jquery

The general method of calling js when loading a page is as follows:

Copy the code The code is as follows:

window.onload = function() {
$("table tr:nth-child(even)").addClass("even"); //This is jquery code
} ;

This code will be executed after all documents on the entire page are loaded. Unfortunately, this method not only requires that the DOM tree of the page be fully loaded, but also requires that all external images and resources be loaded. What's even more unfortunate is that if external resources, such as images, take a long time to load, then this js effect will make the user feel ineffective.

But use the jquery method:

Copy code The code is as follows:

$(document ).ready(function() {
// Any js special effects that need to be executed
$("table tr:nth-child(even)").addClass("even");
});

just needs to load all the DOM structures and execute the js effect before the browser puts all the HTML into the DOM tree. Included before loading external images and resources.

There is also a shorthand way:

Copy the code The code is as follows:

$( function() {
// Any js special effects that need to be executed
$("table tr:nth-child(even)").addClass("even");
});
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