在构建窗口小部件时本地化jQuery变量。我如何在另一个对象中引用jQuery?

时间:2012-06-26 16:30:00

标签: javascript jquery oop scope

我正在关注此tutorial on building a widget

在该教程中,他正在测试页面上是否存在jquery,如果没有,则加载它。

我重新创建了他的代码in this fiddle

我添加了另一个对象CssLoader,但是我无法在该对象中使用jquery。您可以看到我的警报无效。

我应该如何确保在CssLoader和我创建的任何其他对象中提供jquery?

2 个答案:

答案 0 :(得分:1)

我刚刚调整了你的代码

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

DEMO.

答案 1 :(得分:0)

首先,您正在本地化jQuery,然后尝试从另一个匿名函数调用它。你为什么要这样做?

但是,这些文档应该有所帮助:http://docs.jquery.com/Plugins/Authoring