带有日期的JS If语句

时间:2018-08-31 12:48:45

标签: javascript

我想在电子商务网站上添加以下内容:“想要在9月9日星期一之前完成吗?请在2小时24分钟内订购”,在当前日期前加上X天(预计运送天数)。为此,我在网上查找了以下代码:

<div style="text-align: center;font-weight: 400; font-size: 19px; color: #002f40;" id="clockbox"></div>

<script type="text/javascript">
var tday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var tmonth = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."];

function GetClock() {
    var n = 8; // Shipping time
    var today = new Date();
    var d = new Date(today.getFullYear(), today.getMonth(), today.getDate() + n)
    var nday = d.getDay(),
        nmonth = d.getMonth(),
        ndate = d.getDate();

    var clocktext = "<strong>Want it by <span style='color: #af3831;'>" + tday[nday] + ", " + tmonth[nmonth] + " " + [ndate] + " </span>?</strong>";
    document.getElementById('clockbox').innerHTML = clocktext;
}

GetClock();
setInterval(GetClock, 1000);

但是,周日没有交货,我想排除这一天而改为第二天。我试图在这里添加这段代码:

var sunday = tday[nday];
document.getElementById('sundaytext').innerHTML = sunday;

if (sundaytext = "Sunday") {

    var clocktext = "<strong>Want it by <span style='color: #af3831;'> Monday, " + tmonth[nmonth] + " " + [ndate+1] + " </span>?</strong>";
    } else

    var clocktext = "<strong>Want it by <span style='color: #af3831;'>" + tday[nday] + ", " + tmonth[nmonth] + " " + [ndate] + " </span>?</strong>";
    document.getElementById('clockbox').innerHTML = clocktext;

它没有用,并且您可以看到这种方法并不是最聪明的事情,但是我对JS的了解非常有限,因此,我加入了这个论坛来寻求您的帮助。任何意见,高度赞赏!谢谢。

2 个答案:

答案 0 :(得分:1)

除了变量名之外,其他都没问题……应该为if (sunday == "Sunday")(或者您可以使用if(tday[nday]=="Sunday")),但是您使用的是if (sundaytext = "Sunday")。没有这样一个名为'sundaytext的变量在您的代码中。

var sunday = tday[nday];
document.getElementById('sundaytext').innerHTML = sunday;

if (sunday == "Sunday") {
   var clocktext = "<strong>Want it by <span style='color: #af3831;'>Monday, " + tmonth[nmonth] + " " + [ndate+1] + " </span>?</strong>";
} 
else{
  var clocktext = "<strong>Want it by <span style='color: #af3831;'>" + tday[nday] + ", " + tmonth[nmonth] + " " + [ndate] + " </span>?</strong>";    
}
document.getElementById('clockbox').innerHTML = clocktext; 

答案 1 :(得分:0)

应该是:

if (sundaytext == "Sunday") {...}