我试图输入一个时间并让它返回给我,以便我能提醒它。我得到两个错误: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" />
答案 0 :(得分:1)
似乎timeText
是输入字段。在这种情况下,要获取字符串,您必须调用value属性。
我还想对你的功能进行一些改进
400PM
。我对其进行了改进,现在显示4:00PM
。The time is undefined pm
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>