警报输入时间错误返回

时间:2016-03-04 20:36:18

标签: javascript

我试图输入一个时间并让它返回给我,以便我能提醒它。我得到两个错误:1)" time.split不是函数"(我猜是因为我没有传递字符串2)当我尝试将.toString()添加到参数或time.toString()。split(/:/)它没有正确返回。我怎么能让它提醒时间?谢谢!

function changeTime(time) {
    time = time.split(/:/);

    if (time[0] < 12) {
        return (time[0] + time[1] + " AM"); 
    } else if (time[0] == 12) {
        return (time[0] + time[1] + " PM");
    } else if(time[0] > 12) {
        return ((time[0] - 12) + time[1] + " PM");
    } else {
        return("Please enter a valid time!");
    }
}

getTime.addEventListener('click', function() {
    alert("The time is " + changeTime(timeText));
});

编辑:这是我的输入字段&#34; timeText&#34;和&#34; getTime&#34;

   <button id="getTime">Get Time</button>
   <input type="time" id="timeText" />

1 个答案:

答案 0 :(得分:1)

似乎timeText是输入字段。在这种情况下,要获取字符串,您必须调用value属性。

我还想对你的功能进行一些改进

  1. 你的时间显示的是400PM。我对其进行了改进,现在显示4:00PM
  2. 我还检查了时间字段是否有值。只有这样,我才能提醒时间。之前它显示The time is undefined pm
  3. var getTime = document.getElementById("get-time");
    var timeText = document.getElementById("time-text");
    
    function changeTime(time) {
        time = time.split(/:/);
    
        if (time[0] < 12) {
            return (time[0] + ":" + time[1] + " AM"); 
        } else if (time[0] == 12) {
            return (time[0] + ":" + time[1] + " PM");
        } else if(time[0] > 12) {
            return ((time[0] - 12) + ":" + time[1] + " PM");
        } else {
            return("Please enter a valid time!");
        }
    }
    
    getTime.addEventListener('click', function() {
      if (timeText.value) { 
          alert("The time is " + changeTime(timeText.value));
      }
    });
    <input id="time-text" type="time">
    
    <button id="get-time">Get Time</button>