[英]Passing jQuery around as a parameter
If JQuery does exist in scope will these behave in the same way? 如果范围内确实存在JQuery,它们的行为是否会相同?
The $ is used to constrain the scope to inside each function I guess, I'm not exactly sure why however. $用于将范围限制在我猜的每个函数中,但是我不确定为什么。 The second snippet is the original code, I'm attempting to add a check for jquery before it's called as in the first snippet. 第二个片段是原始代码,我试图在第一个片段中调用之前添加对jquery的检查。
First: 第一:
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
main(jQuery);
})();
function main($, undefined) {
alert("main 1");
//do some work on $
}
Second: 第二:
(function ($) {
if (!$) {
alert('Error: JQuery not loaded.');
return;
}
alert("main 2");
//do some work on $
})(jQuery);
Third (Maybe this is slightly better?): 第三(也许这会好一点?):
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
This is the best solution for me. 这对我来说是最好的解决方案。
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.