JavaScript Prompt Box Cancel Button?

后端 未结 6 997
情歌与酒
情歌与酒 2021-01-05 07:27

I have a JavaScript function as follows:

function popup(username) {
var req = createAjaxObject();
var message = prompt(\"Message:\",\"\");
if(message != \"\"         


        
6条回答
  •  借酒劲吻你
    2021-01-05 07:38

    In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).

    So, add an extra explicit check for null inequality:

    if(message != "" && message !== null) {
    

    However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:

    if(message) {
    

    This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.

提交回复
热议问题