【问题标题】:JavaScript: Functions - How to activate cancel buttonJavaScript:函数 - 如何激活取消按钮
【发布时间】:2020-04-07 21:40:14
【问题描述】:

我正在调用 Javascript window.prompt() 并提示用户一次提交一个整数。如果用户在 prompt() 窗口中单击“取消”,该函数应该终止会话,但我找不到解决此问题的函数。

我的问题是,如何在按取消时终止该功能?

这是我的程序:

function isOdd(n) 
{
    return n % 2 == 1; // Checking if the number is odd or not
}


    // sentinel-controlled loop here
    while (true) {
        var n = Number(prompt("Enter an integer (click Cancel to terminate)", "0"));

        if(n === -1) {
            break;
            }
    if(isOdd(n)) {
        alert(n + " is odd.");
        }   
    else {
        alert(n + " is even.");
        }
    }

    // trying to find a solution for cancel button
    //document.getElementById("Button ID").click()

    //function cancel () {
        //var cancelButton = document.getElementById( "cancel");
        //}


    </script>
</head>

<body>
    <form action = "#">
        <input id = "cancel" type = "button" value = "cancel">
    </form>

    <h1>Odd/Even Output</h1>

</body>

【问题讨论】:

  • 您好,我在 Google 上搜索“js 提示取消”,它找到了更早的 StackOverflow question

标签: javascript function button


【解决方案1】:

"如果用户点击取消按钮,该函数返回null。"

var promptResult = prompt(...)

if(!promptResult) {
   break;
}
// parse and rest of the function

【讨论】:

    【解决方案2】:

    如果单击取消按钮,Window.prompt 将返回 null。您需要添加一个案例来处理它。

    var result = prompt("Enter an integer (click Cancel to terminate)", "0");
    if(result === null) {
        return;
    }
    var n = Number(result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2015-08-07
      • 2019-05-25
      • 1970-01-01
      相关资源
      最近更新 更多