function db(a){
$("#p")[0].innerHTML = a;
let b = $("#id_start").dialog({
autoOpen: false,
height: "auto",
width: 400,
modal: true,
resizable: false,
buttons: {
"Yes": function(){
return true;
},
"No": function(){
return false;
}
}
});
$("#id_start").dialog("open");
if (b != true){
return false;
} else {
return true;
}
}
它会立即返回false
我期待它返回真或假,这取决于哪个按钮是按。
发布于 2022-11-04 07:09:32
调用db
时,它将提示用户按“是”或“否”。但是用户可能需要几秒钟才能采取任何行动,这时您的函数已经返回,以便允许页面继续运行其他关键脚本。
这是异步行为,因为在希望采取进一步行动之前,您正在等待发生某些事情(即用户单击一个按钮)。因此,我们需要以这样一种方式编写函数,即它推迟进一步的操作,直到用户进行交互。
一种方法是传递对回调函数的引用。然后,当用户单击“是”或“否”时,我们使用true
或false
调用回调函数
function db ( html, callback ) {
document.querySelector("#p").innerHTML = html;
$("#id_start").dialog({
buttons: {
"Yes": () => callback( true ),
"No": () => callback( false )
}
});
}
那就这样说吧:
db( 'Some new markup', response => {
alert( response ? 'Yes!' : 'No!' );
});
或者,你可以利用一个承诺:
function db ( html ) {
document.querySelector("#p").innerHTML = html;
return new Promise( resolve => {
$("#id_start").dialog({
buttons: {
"Yes": () => resolve( true ),
"No": () => resolve( false )
}
});
});
}
然后以这种方式称呼它:
const userResponse = await db( 'new markup here' );
在上面的场景中,userResponse
要么是true
,要么是false
。
https://stackoverflow.com/questions/74319011
复制相似问题