检测提示上的空值 [英] Detect empty value on prompt

查看:72
本文介绍了检测提示上的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在提示符下按下ok时(以前清空提示字段),如何检测空值?我需要用new(空)值覆盖旧值。我这样做:

How to detect an empty value when user presses ok on prompt (and previously empties the prompt field)? I need to overwrite the old value with the new (empty) value. I'm doing this:

var oldVal = 'something';
var newVal = prompt("Enter new value:", oldVal);

目前,如果用户清空值并点击确定,则返回null。

Currently it returns null if user empties value and clicks ok.

但同时我需要检查空值,因为如果用户单击取消,它将返回null,我不想将其作为新值。

But at the same time I need to check for null value because if user clicks 'cancel', it will return null, which I don't want as new value.

推荐答案

如果用户点击OK,它不返回 null - 它将返回一个空字符串。您可能没有正确测试返回值。如果你想在三种不同的返回状态之间进行测试,你可以这样做:

It does not return null if the user hits OK - it will return an empty string. You are probably not testing the return value properly. If you want to test between the three different return states, you can do that like this:

var oldVal = 'something';
var newVal = prompt("Enter new value:", oldVal);
if (newVal === "") {
    // user pressed OK, but the input field was empty
} else if (newVal) {
    // user typed something and hit OK
} else {
    // user hit cancel
}

工作演示: http://jsfiddle.net/jfriend00/Kx2EK/

您的评论建议您使用此代码测试结果:

Your comment suggests that you're using this code to test the result:

if(!newVal || oldVal == newVal)return false;

当用户清除该字段并按OK时,newVal将为 (空字符串)。 !newVal true 因此您将返回 false 。空字符串是一个假值,就像 null 一样。您需要更明确地检查 null ,如下所示:

When the user clears the field and presses OK, newVal will be "" (an empty string). !newVal will be true so you will return false. An empty string is a falsey value just like null. You need to more explicitly check for null like this:

if (newVal === null || newVal === oldVal) {
    // cancel button was hit
    // or the same value was entered
    return false;
}

这个逻辑的工作演示: http://jsfiddle.net/jfriend00/ynwBx/

Working demo of this logic: http://jsfiddle.net/jfriend00/ynwBx/

注意:我正在使用 === 防止javascript解释器进行任何类型转换,因为我只想显式检查 null

Note: I'm using === to prevent the javascript interpreter from doing any type casting as I want to only explicitly check for null.

这篇关于检测提示上的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆