[英]Unable to call function from one file to another
在我的代碼中,我在file_1.js中定義函數,並從file_2.js調用它,並且文件的順序是
<script type="text/javascript" src="File_1.js"></script>
<script type="text/javascript" src="file_2.js"></script>
誰能幫我從另一個JS文件中調用該函數?
File_1.js
(function( $ ) {
function ps_get_posts( divid, type, query_args, cb) {
var cb = cb || function () {};
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
type: type,
query_args: query_args
},
success: function( html ) {
cb();
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}
})( jQuery );
file_2.js
(function( $ ) {
$(document).ready(function () {
ps_get_posts('#home-section-1 #main', 'card', args);
});
})( jQuery );
ps_get_posts
對定義它的ready
回調完全不公開。 您不能在不以某種方式公開它的情況下從已ready
回調外部調用它。
您可以將其設置為全局,但是瀏覽器上的全局名稱空間非常擁擠,通常最好避免使用全局變量。
一種選擇是將自己限制為單個全局對象,在該對象上可以放置需要在文件之間訪問的功能。 因此,在File1.js
您可以執行以下操作:
var MyApp = {
ps_get_posts: function( divid, type, query_args, cb) {
var cb = cb || function () {};
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
type: type,
query_args: query_args
},
success: function( html ) {
cb();
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}
};
...然后在File2.js中:
MyApp.ps_get_posts(/*...*/);
如果您還有其他功能需要使用相同的方法,請將它們添加到一個全局對象MyApp
。
您的問題不是該函數在另一個文件中,而是在另一個作用域中。 我舉一個例子:
$(function () { function myFunction() { console.log('Hello world!'); } myFunction(); //here the function exists }); myFunction(); //here the function does not exist
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您可以創建一個全局對象來存儲實用程序函數以使其可訪問,就像jQuery那樣:
window.MyUtils= window.MyUtils || {}
window.MYUtils.myFunction= function (...) {...};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.