簡體   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