【问题标题】:Splitting up jquery functions across files?跨文件拆分jquery函数?
【发布时间】:2009-09-19 20:25:25
【问题描述】:

我有几个使用 jquery 的函数,它们在不同的页面上调用。我想知道是否可以在单个文件中定义这些函数,然后在初始文件之后包含的不同文件中调用它们。

这是一个例子:

## default.js
$(function() {
    // jquery specific functions here...
    function showLoader(update_area) {
        update_area.ajaxStart(function() {
            update_area.show();
            $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
        });
    }   
});

## other_file.js (included after default.js)
update_area = $('#someDiv');
showLoader(update_area);

当我这样做时,萤火虫给我'showLoader is not defined。我假设这是因为 $(function() { }); 的范围。其中包含特定于 jquery 的函数。但是,如果是这种情况,这是否意味着我需要在每个调用它们的 js 文件中定义相同的代码?

我怎样才能正确地分开这些东西?

谢谢!

【问题讨论】:

    标签: jquery function split


    【解决方案1】:

    你不必将showLoader的定义放入$(function(){}),而是将showLoader的调用,例如:

    ## default.js
    
    function showLoader(update_area) {
        update_area.ajaxStart(function() {
            update_area.show();
            $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
        });
    }
    
    ## other_file.js
    $(function(){
        update_area = $('#someDiv');
        showLoader(update_area);
    });
    

    $(function(){some_code;}) 是一个jQuery shortcut。它告诉 jQuery 在文档完成加载时运行该代码。

    【讨论】:

    • 谢谢你——我相信这是我想要的答案。
    【解决方案2】:

    写一个插件可能会更好:

    // default.js
    $.fn.showLoader = function() {
        this.ajaxStart(function() {
            this.show();
            $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
        });
    };
    
    
    // other_file.js
    $(function() {
        $('#someDiv').showLoader();
    });
    

    【讨论】:

      【解决方案3】:

      问题不在于您有多个文件,而是 javascript 具有函数作用域,这意味着如果您在函数中定义某些内容(包括另一个函数,就像您对 showLoading 所做的那样),它只能在该函数内部使用.

      function callMe() {
          var foo = 'bar';
          foo; // is 'bar'
      }
      
      foo; // is undefined
      
      
      function callMe() {
          function foo() {}
          foo; // is a function
      }
      foo; // undefined
      

      【讨论】:

        【解决方案4】:

        如果我没记错的话,您需要自己解决依赖关系。 jquery中没有脚本加载工具吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-12
          • 2012-08-16
          • 2020-04-08
          相关资源
          最近更新 更多