【问题标题】:How can I stop execution of javascript function until user action?如何在用户操作之前停止执行 javascript 函数?
【发布时间】:2021-07-17 06:24:12
【问题描述】:

所以我试图在 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;
}

【问题讨论】:

  • 在 JavaScript 中,您不会停止函数的执行,而是使用事件处理程序,当用户执行某项操作时会采取行动。
  • 看看 Sweet Alert 库是如何做到这一点的。
  • 请解释您当前面临的代码存在什么问题。我不明白你的 general foo 函数与它有什么关系。
  • 我在这里看到的唯一问题是您动态加载了一些 HTML 视图,但即使在加载完成之前,您也试图将事件分配给(当前)不存在的元素。您可能想查看带有动态绑定的 Event .on() 或 .load() 成功回调

标签: javascript jquery asynchronous async-await promise


【解决方案1】:

如果您使用的是原始 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 并且有递归限制)),我们只使用一个回调来接收该事件。所以不幸的是,你不能真正将它包装成一个函数......除了可能使用承诺之外?我不认为你可以,但如果你真的出于某种原因坚持使用函数来包装它,那么它可能值得一些研究。

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2017-07-10
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多