jQuery API 返回首页目录 | jQuery API 中英文对照版
ready(fn)
ready(fn)

当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。

这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。 简单地说,这个方法纯粹是对向window.load事件注册事件的替代方法。通过使用这个方法,可以在DOM载入就绪能够读取并操纵时立即调用你所绑定的函数,而99.99%的JavaScript函数都需要在那一刻执行。

有一个参数--对jQuery函数的引用--会传递到这个ready事件处理函数中。可以给这个参数任意起一个名字,并因此可以不再担心命名冲突而放心地使用$别名。 请确保在<body>元素的onload事件中没有注册函数,否则不会触发$(document).ready()事件。 可以在同一个页面中无限次地使用$(document).ready()事件。其中注册的函数会按照(代码中的)先后顺序依次执行。

返回值:jQuery

参数:

  • fn (Function): 要在DOM就绪时执行的函数
 

示例:

$(document).ready(function(){ Your code here... });

示例:

同时使用$(document).ready()和参数来编写应用$别名的具有安全保障(failsafe)的jQuery代码,从而不会依赖于全局别名。

jQuery(function($) {
   // Your code using failsafe $   alias here... 
});
 
ready(fn)

Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.

In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when what 99.99% of all JavaScript code needs to run.

There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risk of naming collisions.

Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.

You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.

Return value: jQuery
Parameters:

  • fn (Function): The function to be executed when the DOM is ready.
 

Example:

 $(document).ready(function(){ Your code here... });  

Example:

Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

 jQuery(function($) {
     // Your code using failsafe $ alias here...   
 });  
相关链接
asp之家 | jQuery官方网站 | jQuery中文网 | 电子书作者网站 | 电子书作者blog