【问题标题】:How to check in Javascript whether variables are null or not? And how to make a message pop up when the variables are null?如何在Javascript中检查变量是否为空?以及如何在变量为空时弹出消息?
【发布时间】:2020-05-03 09:57:57
【问题描述】:

我需要解决这两个问题。

代码如下:

function check() {
  var Name=document.getElementById("Name");
  var Surname=document.getElementById("Surname");
  if (Name==null && Name="" || Surname==null && Surname="") {
    alert("Enter the name or surname");
    return false;
  }
  return true;  
}

基本上,这部分应该做的是:

  • 它应该获取“Name”和“Surname”变量的值
  • 应该检查这两个变量的值是否为空
  • 如果该值确实为空,则应弹出“输入姓名或姓氏”的消息并通知用户输入他/她的姓名/姓氏。

【问题讨论】:

  • Name="" 应该做什么?

标签: javascript


【解决方案1】:

为了获取值,您应该这样做:

var Name=document.getElementById("Name").value;
var Surname=document.getElementById("Surname").value;

并检查用户是否同时输入:

if (Name==null || Name=="" || Surname==null || Surname=="")

【讨论】:

    【解决方案2】:

    您应该使用typeof 进行空值检查,返回的 dom 元素也是一个对象,因此== "" 不起作用。

    function check(){
       var Name=document.getElementById("Name");
       var Cogn=document.getElementById("Surname");
       if (typeof Name === null || typeof Surname === null )
       {
        alert("Enter the name or surname");
        return false;
       }
       return true;  
    }
    

    【讨论】:

    • typeof var 返回一个字符串值,因此 typeof null'object' 并确保它真的是 null 正确的检查是三等号 null === null // is true
    【解决方案3】:

    使用三元组不仅可以检查一个值,还可以检查它的类型。

    if (Name===null || Surname===null) {
    

    如果是假值,只需使用if (!Name || !Surname),然后它会检查空值、空字符串、假和未定义。

    单个等于分配,if (Name==null && Name="") - 将 Name 设置为空字符串,不确定它是否是所需的流程。

    如果NameSurname是html的input标签,那么它们的值是字符串类型,在.value属性下。

    在这种情况下,代码应该是这样的

    var Name=document.getElementById("Name").value.trim(); // avoid spaces
    var Surname=document.getElementById("Surname").value.trim(); // avoid spaces
    if (Name==="" || Surname==="")
    {
      alert("Enter the name or surname");
      return false;
    }
    return true;    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2014-05-03
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多