[英]Immediately Invoked Function Expression and document ready function
在使用jQuery的Javascript中,我可以使用立即调用的函数表达式将范围添加到函数中,并传递函数jQuery,并命名参数$
(function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
};
}( jQuery ));
同样,我们编写文档准备功能如下
$(function() {
console.log( "ready!" );
// use $ variable here
});
这是否意味着文件就绪功能已经确定范围?
我是否还需要传递函数jQuery,并在文档就绪函数中命名参数$? 像下面这样
$(function ( $ ) {
console.log( "ready!" );
// use $ variable here
}( jQuery ));
IIFE被立即调用,它不会等待document
准备就绪。 所以:
(function($) {
// here document is not necessarly ready
})(jQuery);
当您执行$(function() { ... });
您不是在创建IIFE,而是只是传递了准备好document
时要执行的函数(回调)。
如果您想两者都做,请使用:
(function($) {
$(function() {
// here, document is really ready
// $ available here too
});
})(jQuery);
或这样做(使用jQuery 将自身作为参数传递给ready回调的事实):
jQuery(function($) {
// here, document is really ready
// and $ is obviously available (only here)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.