问题
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.
回答1:
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;
}
}
回答2:
You should explicitly check for null as the return value (using triple-equals) and return when this is the result.
var result = prompt("OK?");
if (result === null) {
return;
}
This allows you to distinguish from the empty string, which is what's returned when the user clicks OK but enters no content.
回答3:
One substantial problem with handling the result of 'prompt' is that Safari (at least version 9.1.2) returns "" instead of null when "Cancel" is clicked. This means that: if(result==null) return; does not work, and you cannot distinguish between entry of a null string, and cancellation.
回答4:
Can you just check for
if (prompt_responce == null)
to tell if it is closed.
回答5:
Try:
message = prompt("Enter text");
if(message == "null" || message == null || message == "" );
This worked for me.
来源:https://stackoverflow.com/questions/12864582/javascript-prompt-cancel-button-to-terminate-the-function