Javascript"空"功能验证器

时间:2016-12-06 21:20:26

标签: javascript

我是Javascript的新手,我想提醒用户,如果Javascript中的字段为空,则使用函数....我已经设置了一个程序我只需要添加另一个'空&# 39;功能....这是我到目前为止...提前感谢您的帮助。



var time = 0;

function printTime() {
  time = prompt("Please enter the time in 24 hour clock format eg 00:00 ");
  
  function isEmptyTime() {
    var time = time.split(":");
    var hours = parseInt(time[0]);
    var minutes = parseInt(time[1]);

    if (time == "00:00") {
      document.write("Midnight");
    } else if (time == "12:00") {
      document.write("Noon");
    } else if (hours < 12) {
      document.write("" + hours + ":" + minutes + " AM");
    } else if (hours >= 12 && hours < 24) {
      hours = hours - 12;
      document.write("" + hours + ":" + minutes + " PM");
    } else(time.length == 0) {
      document.write("No data has been entered");
    }
  }
}

printTime();
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

基本上,这里有一些不正确的项目。首先,你有一个你永远不会调用的内部函数。我将此功能移到了printTime()之外。其次,最后else块必须是else if。最后,您在重新定位的isEmptyTime()方法中多次重复使用时间变量。

这应该适合你:

var time = "";

function isEmptyTime(time) 
{
  var t = time.split(":");
  var hours = parseInt(t[0]);
  var minutes = parseInt(t[1]);
  var result = "";
  
  if (time == "00:00")
  {
    result = "Midnight";
  } 
  else if (time == "12:00") 
  {
    result = "Noon";
  } 
  else if (hours < 12) 
  {
    result = "" + hours + ":" + minutes + " AM";
  }
  else if (hours >= 12 && hours < 24) 
  {
    hours = hours - 12;
    result = "" + hours + ":" + minutes + " PM";
  }
  else if (time.length == 0) 
  {
    result = "No data has been entered";
  }
  console.log(result);
}

function printTime() 
{
  time = prompt("Please enter the time in 24 hour clock format eg 00:00 ");
  isEmptyTime(time);
}

printTime();