web*_*dia 26 jquery document-ready iife
我正在看一段代码:
(function($) {
// other code here
$(document).ready(function() {
// other code here
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
我虽然IIFE执行$(document).ready的功能,这段代码是否正确?或者我可以删除$(document).ready并将代码直接放在IIFE中.
Bho*_*yar 49
不,IIFE不执行文档准备中的代码.
(function($) {
console.log('logs immediately');
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
此代码立即运行"立即记录日志",而文档已准备就绪.
(function($) {
$(document).ready(function(){
console.log('logs after ready');
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
立即运行代码并等待文档准备就绪并记录"准备好后的日志".
这可以更好地理解:
(function($) {
console.log('logs immediately');
$(document).ready(function(){
console.log('logs after ready');
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这会在窗口加载后立即将"立即记录"记录到控制台,但只有在文档准备好后才会记录"准备好后记录".
替代方案$(document).ready(function(){})是:
$(function(){
//code in here
});
Run Code Online (Sandbox Code Playgroud)
从jQuery 3.0版开始,就绪处理程序已更改.
jQuery(function($) {
});
Run Code Online (Sandbox Code Playgroud)
$(function() {
console.log("inside handler");
});
console.log("outside handler");
Run Code Online (Sandbox Code Playgroud)
>外部处理程序
>内部处理程序
$(function() {/* DOM Manipulations goes here})(function($) {/* safely use $ here*/}(jQuery))你可以结合两种方法:
(function($) {
/*Do smth that doesn't require DOM to be ready*/
$(function() {
/*Do the rest stuff involving DOM manipulations*/
});
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15441 次 |
| 最近记录: |