我正在尝试从另一个js文件中的一个文件调用函数。
general.js
function delete_post(post_id, post_type, nonce) {
$.post(Ajax.ajaxurl, { action: 'delete_post', post_id: post_id, nonce: nonce, post_type: post_type}, function (data) {
var result = $.parseJSON(data);
if (result.status == 'error') {
$('#post_'+post_id).prepend('<div class="alert alert-danger">' + result.message + '</div>');
}
if (result.status == 'success') {
$('#post_'+post_id).fadeOut(1000, function(){
$(this).remove();
});
}
});
}
details.js
$('body').on('click', '.remove-row', function (e) {
e.preventDefault();
var post_id = $(this).attr('data-target');
var nonce = $(this).attr('data-nonce');
var parent_id = $(this).attr('data-parent');
var post_type = $(this).attr('data-post_type');
bootbox.confirm(Ajax.are_you_sure, function(result) {
if (result) {
delete_post(post_id, post_type, nonce);
}
});
});
在页面上,它们以正确的顺序加载:
<script type='text/javascript' src='http://domain.com/js/general.js?ver=3.9.1'></script>
<script type='text/javascript' src='http://domain.com/js/details.js?ver=3.9.1'></script>
但是,当我单击
remove-row
按钮时,会得到Uncaught ReferenceError: delete_post is not defined
。我想念什么?
最佳答案
该错误告诉我们您没有完全显示general.js
,特别是delete_post
的函数声明在另一个函数内部(下面是一个可能的示例)。因此,这不是全球性的。
如果要使其成为全局变量,可以通过将以下行放在general.js
中来实现:
window.delete_post = delete_post;
window
对象的属性是全局变量。通常,我建议将全局变量保持在最低限度,因此,您可能希望针对所有内容使用单个全局对象,具体做法如下:
if (!window.myApp) {
window.myApp = {};
}
window.myApp.delete_post = delete_post;
...然后代替
delete_post(post_id, post_type, nonce);
...在您的其他文件中,使用
myApp.delete_post(post_id, post_type, nonce);
当我说它在另一个函数中时,这里是一个例子:
$(document).ready(function() {
function delete_post() {
// ...
}
});
您的示例可能看起来略有不同,但这就是要点。
关于javascript - Javascript-无法从另一个文件调用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23977815/