繁体   English   中英

如何在用户操作之前停止执行 javascript 函数?

[英]How can I stop execution of javascript function until user action?

所以我试图在 javascript 中复制 window.confirm() 提示。 这是我尝试过的结构。

function foo(){
    if(customConfirm("Click yes or no"))
        alert("Clicked yes");
    else
        alert("Clicked no");
}

function customConfirm(message){
    $('#customConfirm').load("customAlert.html");
    $('#okButton').click(function(e){
        ret = true;
    })
    $('#cancelButton').click(function(e){
        ret = false;
    })
    return ret;
}

如果您使用原始 JS,或者最多使用 JQuery 而不是 React、Vue 等,我将为“customConfirm”提供回调,以便当您检测到按下 Ok 和 Cancel 按钮时,并相应地调用每个回调. 这将需要使用事件处理程序,这对于原始 JS 来说是相当基本的,对于 JQuery 更是如此......

这是我所说的基本思想(如果代码不正确,请原谅我,我已经有一段时间没有使用 JQuery,更不用说前端 JS。

function displayConfirm() {
    // Let's pretend the confirm "modal" has two buttons, one with id "okButton" and the other with "cancelButton". We shall use this later.
}

function updatePage(cancelled) {
    // Here is where we would update the page depending on whether or not the confirm was cancelled. 
}
$('#okButton').click(function() { // We don't use e, so we're just gonna ignore it... I think you can anyways, if JQuery throws a fit, use _ instead of e for the variable name as it just tells JS "hey, this variable, we don't use it."
    updatePage(false);
}); // Consistently use semicolons, look into ESLint if you're forgetful like me lol
$('#cancelButton').click(function() {
    updatePage(true);
});

就这么简单。 由于 JS 不允许您像那样暂停执行(好吧,您可以,但它只会冻结其他所有内容,例如当您永远不会从无限循环中中断,或在没有退出条件的情况下递归时(除非 JS 执行Python 并且有递归限制)),我们只在接收到该事件时使用回调。 所以不幸的是,你不能真正把它包装成一个函数......除了可能使用承诺? 我不认为你可以,但如果你真的,无论出于何种原因坚持使用一个函数来包装它,这可能值得进行一些研究。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM