2009-09-19 55 views
2

我有幾個使用jquery的函數在不同的頁面之間調用。我想知道是否可以在單個文件中定義這些函數,然後在初始文件後包含的不同文件中調用它們。跨文件拆分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沒有定義。我假設這是因爲$(function(){})的範圍;其中包含jQuery特定的功能。但是,如果是這種情況,那並不意味着我需要使用相同的代碼來定義我稱之爲的每個js文件中的函數?

我該如何正確區分這些東西?

謝謝!

回答

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); 
}); 

$(function(){some_code;})是一個jQuery shortcut。它告訴jQuery在文檔完成加載時運行該代碼。

+0

感謝您 - 我相信這是我想要的答案。 – 2009-09-19 23:03:21

0

如果我沒有弄錯,你需要自己解決依賴關係。 jquery中沒有腳本加載器工具嗎?

4

這可能是最好編寫一個插件:

// 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(); 
}); 
2

的問題不在於你有多個文件,但JavaScript有功能範圍,這意味着如果你定義的東西(包括其他功能,如你用showLoading做的)在一個函數內,它只會在該函數內部可用。

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

foo; // is undefined 


function callMe() { 
    function foo() {} 
    foo; // is a function 
} 
foo; // undefined