Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

Javascript prompt() - cancel button to terminate the function

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.

question from:https://stackoverflow.com/questions/12864582/javascript-prompt-cancel-button-to-terminate-the-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...