The first thing to learn about jQuery is: if you want an event to run on your page, you must call the event in $(document).ready(). All elements or events included in $(document).ready() will be loaded immediately after the DOM has finished loading, and before the page content is loaded.
If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as theDOM is loaded and before the page contents are loaded.
$(document).ready(function() {
// put all your jQuery goodness in here.
});
There are many ways to ensure that events work properly on the page, $(document).ready() is better than others More advantages. First, you don't have to put any "behavioral" markup on your HTML. In addition, you can write JavaScript/jQuery into a separate js file, which is easy to maintain and ensures the isolation of js and page content. If you are more careful when browsing the web, you will often see this situation: when you hover the mouse over a connection, sometimes a message like "javascript:void()" will be displayed in the status bar. This is what happens when you put an event directly inside the
tag.
In some pages using traditional JavaScript, you will see the "onload" attribute in the tag. This causes a problem: it limits there to only be one function event on the body. Yes, because it adds a "behavioral" tag to the content. If you want to solve this problem, please refer to Jeremy Keith's book: DOM Scripting, which describes how to create an "addLoadEvent" function in a single js file, which allows multiple functions to be loaded in the body. But this method requires writing a considerable amount of code for an otherwise simple problem. In addition, this method triggers these events when the window is loaded, which has to remind me again of the benefits of $(document).ready() .
Using $(document).ready(), you can have your events load or fire before the window loads. Everything you write in this method is ready to be loaded or triggered at the earliest possible moment. In other words, once the DOM is registered in the browser, the code in $(document).ready() starts executing. This way, the special effects can run when the user first sees the page element.