我跟随此tutorial on building a widget构建小部件时本地化jQuery变量。我如何在另一个对象中引用jQuery?
在该教程中,他测试jquery是否存在于页面上,如果没有,加载它。
我重新他的代码in this fiddle
我已经添加了另一个对象,CssLoader,但我无法使用该对象内部的jQuery。你可以看到我的警报不起作用。
我应该如何确保jQuery在CssLoader和其他创建的对象中可用?
我跟随此tutorial on building a widget构建小部件时本地化jQuery变量。我如何在另一个对象中引用jQuery?
在该教程中,他测试jquery是否存在于页面上,如果没有,加载它。
我重新他的代码in this fiddle
我已经添加了另一个对象,CssLoader,但我无法使用该对象内部的jQuery。你可以看到我的警报不起作用。
我应该如何确保jQuery在CssLoader和其他创建的对象中可用?
我刚刚调整了你的代码
var CssLoader = (function(){
var $=''; //the global $ inside CssLoader
function init($, cssPathArray){ // Receive the jquery in the first argument
$=jq; // assign jQuery to global $, so it'll be available inside CssLoader
alert($('body'));
}
return {
init : init
};
})();
而且内部函数调用main
CssLoader.init
如下
CssLoader.init($, ['cssPath1', 'cssPath2']); // Pass the jquery in the first argument
首先,您正在本地化jQuery,然后尝试从另一个匿名函数调用它。你为什么要这样做?
然而,这些文档应该有所帮助:http://docs.jquery.com/Plugins/Authoring
谢谢。这将工作,但这将意味着我将不得不将jquery传递到我创建的每个对象(需要它)。我希望避免这种情况。 – Finnnn
不,您应该首先调用init,以便它可以在全球范围内使用,但这是正确的方法,我只是稍微调整了一下代码。检查演示,有两个警报。不用谢! –