提示:如何知道用户取消或提交空值

时间:2017-06-30 17:25:49

标签: javascript

提示有三个阶段:

  1. PRESSED Ok with value
  2. PRESSED Ok with empty value
  3. 按下取消
  4. 如何确定2到3之间?

    更新

    即示例

    <component v-model='foo' :is='boo' ...>

    更新2

    它似乎在Chrome和其他浏览器中运行良好。但不在2和3相同的野生动物园中。提交空输入就像取消一样。

3 个答案:

答案 0 :(得分:1)

  1. 检查非空字符串(result
  2. 检查空字符串(result === ""
  3. 检查nullresult === null
  4. 了解propmt()是浏览器功能的一部分非常重要。它不是由JavaScript / ECMAScript标准定义的,因此,它们的实现细节因浏览器而异。通常,如果按下 CANCEL ,则propmt()中输入的内容无关紧要,将返回null

    var response = prompt("What is your name?");
    
    // You should always call the string.trim() method on user input which will
    // remove any leading or trailing spaces from the string. This prevents strings
    // that are nothing but spaces or valid answers that have spaces around them.
    if(typeof response === "string"){
      response = response.trim();
    }
    
    // The first test tests for "truthy" values (anything that is not:
    // 0, null, undefined or false. So any typed characters mean truthy.
    if(response) {
        alert("You typed something: " + response);                                   // Ok with value
    } else if(response === ""){
        alert("You clicked OK but didn't type anything or just typed spaces"); // Ok with empty value, AND cancel
    } else if(response === null){
        alert("You hit Cancel");                          // Cancel was hit
    }

答案 1 :(得分:0)

Window.prompt()

  

result是一个包含用户输入的文本的字符串,或者为null。

&#13;
&#13;
let result = window.prompt("Meow?");
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

这里有一个注释:https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt在Safari中说取消将以空字符串形式返回,并且无法区分。

在Chrome中,变量在取消时设置为null,在用户单击“ok”时设置为空字符串。