我跟隨此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,以便它可以在全球範圍內使用,但這是正確的方法,我只是稍微調整了一下代碼。檢查演示,有兩個警報。不用謝! –