我有一个圣诞节倒计时时钟工作正常,但是,当它显示1小时时,它说1'小时'不是1'小时'
我知道这有点小事,但我希望它是正确的,并显示正确的单词。
有人可以帮忙吗?
守则
<script language="javascript" type="text/javascript">
today = new Date();
BigDay = new Date("December 25, 2013")
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft)*24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft)*60);
document.write( "There's only "+daysLeft+" days, "+hrsLeft+" hours and "+minsLeft+" minutes left until Christmas!");
</script>
非常感谢PBrown
答案 0 :(得分:1)
(作为旁注,you probably shouldn't use document.write
)。
这是使用JS的ternary operator。
的好地方var hoursStr = hrsLeft === 1 ? hrsLeft + 'hour' : hrsLeft + 'hours';
答案 1 :(得分:1)
today = new Date();
BigDay = new Date("December 25, 2013");
msPerDay = 24 * 60 * 60 * 1000;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft) * 24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft) * 60);
document.write("There's only " + daysLeft + getDayText(daysLeft) + " , " + hrsLeft + getHourText(hrsLeft) + " and " + minsLeft + getMinuteText(minsLeft) + " left until Christmas!");
function getHourText(hour) {
if (hour > 1) {
return " hours";
}
return " hour";
}
function getMinuteText(min) {
if (min > 1) {
return " minutes";
}
return " minute";
}
function getDayText(day) {
if (day > 1) {
return " days";
}
return " day";
}
编辑:上面当然是漫长的做法,绝对不是大多数人的首选方式。您也可以使用三元运算符并执行以下操作:
var str = hours + (hours > 1 ? " hours " : " hour ") + "left!";
答案 2 :(得分:0)
function pluralize(num, str){
if(num > 1){
return num+' '+str+'s';
}
return num+' '+str;
}
使用
var hrsLeft = 20;
pluralize(hrsLeft, 'hour');
返回
20 hours
这是非常基本的,它存在这个功能的更完整版本。
请点击此处查看完整的pluralize