是否可以让 JS 函数的返回取决于用户操作?
假设我有函数 a 和函数 b。
函数 b 会打开一个带有两个按钮的对话框,一个返回 true,一个返回 false。我可以从 a 调用 b 并强制 a 在继续操作之前等待 b 的返回吗?
示例代码:
function a(){
if(b()){
do x
}else{
do y
}
}
function b(){
$("#anElement").dialog({
title: "This is a Dialog",
buttons:{
"Yes": function(){
//do some stuff
$(this).dialog("close");
return true;
},
Cancel: function(){
//do some stuff
$(this).dialog("close");
return false;
}
}
});
}
我想这很像一个确认,但我想在它之上构建的不仅仅是是/否。有什么建议吗?
最佳答案
不,您不能停止函数的执行(好吧,您可以使用带有中断条件的无限 while 循环,但这是糟糕的做法)。但是,您可以将 A 拆分为两个函数并从函数 B 调用函数 A 的另一半。您甚至可以将返回函数传递给函数 B 并调用它,传递用户操作的值。
示例:
function A() {
// do stuff
B(finishA);
}
function B(callback) {
if(someCondition) {
callback(true);
} else {
callback(false);
}
}
function finishA(userInput) {
if(userInput) {
// do something if the user clicked okay
} else {
// do something if the user clicked cancel
}
}
关于javascript - 是否可以让 JS 函数的返回取决于用户操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10501183/