【问题标题】:Localize jQuery variable while building a widget. How do I refer to jQuery in another object?在构建小部件时本地化 jQuery 变量。如何在另一个对象中引用 jQuery?
【发布时间】:2012-06-28 00:53:53
【问题描述】:

我正在关注这个tutorial on building a widget

在那篇教程中,他正在测试页面上是否存在 jquery,如果不存在,则加载它。

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

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

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

【问题讨论】:

    标签: javascript jquery oop scope


    【解决方案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.

    【讨论】:

    • 谢谢。这会起作用,但这意味着我必须将 jquery 传递给我创建的每个对象(需要它)。我希望避免这种情况。
    • 不,您应该先调用 init,这样它才能在全球范围内可用,但这是正确的方法,我只是稍微调整了您的代码。查看演示,有两个警报。不客气!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-07-19
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 2012-08-29
      • 1970-01-01
      相关资源
      最近更新 更多