所以我有一个函数,它通过AJAX提交东西,然后显示一个对话框,如果它成功与否。所有的工作都很好,但然后我想传递一个额外的对话函数(可选)的选项,这将执行额外的功能。我有:
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
alertDialog('Supplier '+ action +' successfully!','Success',$('#manage-suppliers-form :input:visible:first').focus());
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction()
});
}
1)如果我传递一个closeFunction
,上面就不起作用了2)我甚至没有测试过它——没有传递给它一些东西,但我肯定它也不会工作。closeFunction应该是OPTIONAL
3)我不能简单地将'focus'行代码放在alertDialog调用之后。即使这是有效的(在背景中获得焦点)。一旦有人在alertDialog上点击"ok",焦点就丢失了——因此需要在alertDialog关闭时调用。
首先,无论您在问题中提到的是什么(将函数传递给函数),在Javascript编程世界中都被称为"callback"函数。
顺便说一句,为了回答你的问题,我想你需要绑定关闭事件回调函数,当你关闭对话框时调用,如下所示:
var that = this;
dialog.dialog({
close: function( event, ui ) {
if(closeFunction && typeof closeFunction === 'function') {
closeFunction.call(that);
}
}});
在closeFunction中,尝试对所需的元素执行focus()。
试着读一下这个!为了更好地理解关闭事件回调的用法。
如果你仍然没有得到一个适当的解决方案,从我的回答,请张贴小提琴或给你面对的问题更好的理解!
Try
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
//Pass the function as the fourth parameter and create a annonymous function to set the focus
alertDialog('Supplier '+ action +' successfully!', 'Success', '', function(){
$('#manage-suppliers-form :input:visible:first').focus();
});
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction //assign the function reference instead of the return value of the function
});
}