在文件中拆分jquery函数?

Ste*_*e K 2 jquery split function

我有几个使用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);
Run Code Online (Sandbox Code Playgroud)

当我这样做时,firebug给我'showLoader没有定义.我假设那是因为$(function(){})的范围; 其中包含特定于jquery的函数.如果是这种情况,那么,这是不是意味着我需要使用相同的代码来定义每个js文件中的函数?

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

谢谢!

Ben*_*end 5

您不必将定义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);
});
Run Code Online (Sandbox Code Playgroud)

$(function(){some_code;})是一个jQuery快捷方式.它告诉jQuery在文档加载完成后运行该代码.