简体   繁体   English

无法检测到用户从window.prompt()中按下“取消”

[英]Unable to detect user pressing 'Cancel' from window.prompt()

According to what I've researched, the function should be able to detect whether input is empty or not as well as if 'Cancel' is pressed. 根据我的研究,该功能应该能够检测输入是否为空以及是否按下了“取消”。 However, only the first two things work and whenever I click on 'Cancel', nothing happens. 但是,只有前两项有效,并且每当我单击“取消”时,都不会发生任何事情。

I've posted the whole function code, but my issue is with the if-else statement. 我已经发布了整个功能代码,但是我的问题是if-else语句。 I've tested this on IE7, Chrome and Firefox. 我已经在IE7,Chrome和Firefox上对此进行了测试。

JavaScript: JavaScript:

function countStrings()
{
    var sequence = [];
    sequence = window.prompt( "Enter a sequence of values", "a 1 b 2" ).split( " " );
    if ( sequence[ 0 ] === "" )
    {
        // user pressed OK or Return; input is empty
    }
    else if ( sequence )
    {
        // user pressed OK or Return; input not empty.
    }
    else
    {
        // User pressed Cancel; not being detected/not working.
        // Nothing happens.
    }
}

HTML: HTML:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Practice</title>
    <script type = "text/javaScript" src="./practice.js"></script>
</head>
<body id="beach_ready">
    <h1>Practising JavaScript functions</h1>
    <p>
        <input id="f" type="button" value="Function" onclick="countStrings();" />
        Click to the count number of strings in an array
    </p>
</body>
</html>
var sequence=window.prompt();

if (sequence===""){
//then I entered nothing and pressed OK
} else
if (sequence===null){
//then I pressed cancel.
} else {
//then I entered something good. process it
//..rest of your code...
}

To answer your question: null.split(" "); 回答您的问题: null.split(" "); results in an error, because you can't call any methods on null , because its null and isn't an object and doesn't have methods to call. 导致错误,因为您不能在null上调用任何方法,因为它的null和不是对象并且没有要调用的方法。

So when this line happens 所以当这条线发生时

sequence = window.prompt( "Enter a sequence of values", "a 1 b 2" ).split( " " );

and the user presses cancel, this evaluates to sequence = null.split(" ") and your script bombs out. 然后用户按“取消”,则结果为sequence = null.split(" ") ,脚本被炸毁。 So you need to get the value first, see what it is, then don't call split on it until you have determined it's safe to do so. 因此,您需要首先获取值,看看它是什么,然后在您确定这样做是安全的之前,不要对其进行调用。 Like this: 像这样:

var sequence, sequenceInput;
    sequenceInput = window.prompt( "Enter a sequence of values", "a 1 b 2" );
    if ( sequenceInput=== "" )
    {
        // user pressed OK or Return; input is empty
    }
    else if ( sequenceInput===null )
    {
        // user pressed cancel
    }
    else
    {
        //user entered something
        sequence=sequenceInput.split(" ");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM