Javascript prompt() - cancel button to terminate the function

后端 未结 5 1107
自闭症患者
自闭症患者 2020-12-14 06:19

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). Th

5条回答
  •  时光取名叫无心
    2020-12-14 06:31

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

提交回复
热议问题