Javascript提示符() - 取消按钮来终止该功能 [英] Javascript prompt() - cancel button to terminate the function

查看:78
本文介绍了Javascript提示符() - 取消按钮来终止该功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调用一个Javascript window.prompt()并提示用户提交一个变量,我将它与另一个变量进行比较(一个非常基本的密码保护)。但是,如果在提示符()窗口中单击cancel,该功能将很有用,该功能不会简单地终止,而是将变量与一个空字符串进行比较(用户选择不通过按取消来提交),导致函数继续到 else {} 部分。



我的问题是,如何在按取消时终止该功能?我只需要知道如何定位取消按钮。

通常我会在 click()上调用 .stop() / code>一个按钮,但我不知道如何定位到提示窗口的取消按钮。

解决方案

提示符 OK ''没有提交任何值),则返回一个字符串。如果用户按下取消,则返回 null 。所有你需要做的是检查值是 null

 函数doSomething(){
var input;
input = prompt('做点什么?');
if(input === null){
return; //
}
switch(input){
case'fun':
doFun();
休息;
case'boring':
beBoring();
休息;
}
}


I'm calling a Javascript window.prompt() and prompting the user to submit a variable which I compare to another variable (a very basic password protection). The function works great, however, if you click "cancel" on the prompt() window, the function does not simply terminate, but rather compares the variable to an empty string, (which the user opted not to submit by pressing "cancel" instead) resulting in the function continuing to the else{ } portion.

My question is, how do I terminate the function upon pressing cancel? I just need to know how to target the cancel button.

Usually I would just call a .stop() on the click() of a button, but I don't know how to target the prompt-window's cancel button.

解决方案

prompt returns a string if the user presses OK ('' being with no value submitted). If the user pressed Cancel, null is returned. All you need to do is check whether the value is null:

function doSomething() {
    var input;
    input = prompt('Do something?');
    if (input === null) {
        return; //break out of the function early
    }
    switch (input) {
    case 'fun':
        doFun();
        break;
    case 'boring':
        beBoring();
        break;
    }
}

这篇关于Javascript提示符() - 取消按钮来终止该功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆