在我的代码中,我在 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
回调完全私有(private)。如果不以某种方式公开它,您就无法从 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
中。
关于javascript - 无法从一个文件调用函数到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46070941/