简体   繁体   English

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

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

So im trying to replicate the window.confirm() prompt in javascript.所以我试图在 javascript 中复制 window.confirm() 提示。 here is the structure of what i tried.这是我尝试过的结构。

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;
}

If you're using raw JS, or at most JQuery instead of say React, Vue, etc., I would provide callbacks for the "customConfirm" so that say when you detect a button press on Ok and Cancel, and call each callback accordingly.如果您使用原始 JS,或者最多使用 JQuery 而不是 React、Vue 等,我将为“customConfirm”提供回调,以便当您检测到按下 Ok 和 Cancel 按钮时,并相应地调用每个回调. This would require the use of event handlers which is fairly basic with raw JS, and even more so with JQuery...这将需要使用事件处理程序,这对于原始 JS 来说是相当基本的,对于 JQuery 更是如此......

Here's a basic idea of what I'm saying (forgive me if the code is incorrect, I haven't used JQuery let alone frontend JS in some time now.这是我所说的基本思想(如果代码不正确,请原谅我,我已经有一段时间没有使用 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);
});

It's as simple as that.就这么简单。 Since JS doesn't allow you to just pause execution like that (well you can, but it just freezes everything else, such as when you don't ever break from an infinite loop, or recurse with no exit condition (unless JS does a Python and has a recursion limit)), we use just a callback for when that event is received.由于 JS 不允许您像那样暂停执行(好吧,您可以,但它只会冻结其他所有内容,例如当您永远不会从无限循环中中断,或在没有退出条件的情况下递归时(除非 JS 执行Python 并且有递归限制)),我们只在接收到该事件时使用回调。 So unfortnately afaik you can't really wrap this into a function... Aside of maybe using promises?所以不幸的是,你不能真正把它包装成一个函数......除了可能使用承诺? I don't think you can but it may be worth some research if you really, for whatever reason insist on using a function to wrap it all.我不认为你可以,但如果你真的,无论出于何种原因坚持使用一个函数来包装它,这可能值得进行一些研究。

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

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