gpt4 book ai didi

javascript - 如何使函数在完成特定任务之前不返回?

转载 作者:行者123 更新时间:2023-12-03 08:17:41 25 4
gpt4 key购买 nike

因此,我编写了一个函数来模拟 JavaScript 的功能confirm框。

如何使函数在完成特定任务之前不返回?这里mconfirm返回undefined 。我要回truefalse基于用户点击 Yes/Cancel 。我怎样才能做到这一点?

var mconfirm = function(message) {
if(!message)
message = "Remove the selected item?";
$("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
$( "#dialog-confirm" ).dialog({
resizable: false,
modal: true,
buttons: {
Yes: function() {
$( this ).dialog( "close" );
return true;
},
Cancel: function() {
$( this ).dialog( "close" );
return false;
}
}
});
};

最佳答案

您不能等待此类操作完成后再返回。(关闭对话框与从任何地方获取输入一样异步)

在 JS 中,您通常为用户提供一种方法来传递操作完成时调用的函数。 (即传递回调)。

var mconfirm = function(message, callback) {
if(!message)
message = "Remove the selected item?";
$("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
$( "#dialog-confirm" ).dialog({
resizable: false,
modal: true,
buttons: {
Yes: function() {
$( this ).dialog( "close" );
// Pass whatever you want to the callback
callback("yes");
return true;
},
Cancel: function() {
$( this ).dialog( "close" );
// Pass whatever you want to the callback
callback("cancel");
return false;
}
}
});
};

并且,不要做类似的事情:

var result = mconfirm("Are you sure ?");
// result is "yes" or "cancel"

调用者会这样做

mconfirm("Are you sure", function(result) {
// result is "yes" or "cancel"
});

关于javascript - 如何使函数在完成特定任务之前不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33867337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com