1

我需要你的帮助。在到处搜索之后,我找不到我需要的正确答案。我正在尝试创建一个 javascript 函数来根据一天中的时间更改链接 href 值。(即,我希望将用户连接到我们的帮助台的链接在中部标准时间晚上 11:45 停用并在中部标准时间上午 7 点激活。)我在网上找到了一个旧功能,可以让它工作,但它有一个开始日期,我是 javascript 新手所以我不知道如何将其更改为仅使用一天中的时间的位置。因此,如果您可以查看代码并建议如何修改它以使其仅在当天工作,或者提供另一种替代方案,我将不胜感激!

<script type="text/javascript">
var startDay = 5; // Start Day: 0 - 6 (Sun = 0, Mon = 1 ... Fri = 5, Sat = 6)
var startHour = 16; // Start Hour: 0 - 23
var startMin = 8; // Start Min: 0 - 59
var endDay = 5; // End Day: 0 - 6 (Sun = 0, Mon = 1 ... Fri = 5, Sat = 6)
var endHour = 16; // End Hour: 0 - 23
var endMin = 10; // End Min: 0 - 59

function alternateLink(linkObj)
{
var startTimeDate = new Date(2012, 01, 01, startHour, startMin, 00);
with (startTimeDate) while (getDay() != startDay) setDate(getDate()+1);
var startTimeDateMsecs = startTimeDate.getTime();

var endTimeDate = new Date(2012, 01, 01, endHour, endMin-1, 00);
with (endTimeDate) while (getDate() < startTimeDate.getDate()) setDate(getDate()+1);
with (endTimeDate) while (getDay() != endDay) setDate(getDate()+1);
var endTimeDateMsecs = endTimeDate.getTime();

var now = new Date();
var currentTimeDate = new Date(2012, 01, 01, now.getHours(), now.getMinutes(), 00);
with (currentTimeDate) while (getDate()<startTimeDate.getDate()) setDate(getDate()+1); 
with (currentTimeDate) while (getDay() != now.getDay()) setDate(getDate()+1);
var currentTimeDateMsecs = currentTimeDate.getTime();

if (currentTimeDateMsecs >= startTimeDateMsecs && currentTimeDateMsecs <=endTimeDateMsecs) linkObj.href = 'contactus.php';} 
</script>    


<img src="default.png" alt="Time Image" id="image_id">
4

1 回答 1

0

使用getDategetMonth功能getFullYear

var now = new Date();
var month = now.getMonth()+1; //return range is 0-11, so add 1
var day = now.getDate();
var year = now.getFullYear();

var startTimeDate = new Date(year, month, day, startHour, startMin, 00);
...
var startTimeDateMsecs = startTimeDate.getTime();

var endTimeDate = new Date(year, month, day, endHour, endMin-1, 00);
...
var endTimeDateMsecs = endTimeDate.getTime();

var currentTimeDateMsecs = now.getTime();

if (currentTimeDateMsecs >= startTimeDateMsecs && currentTimeDateMsecs <=endTimeDateMsecs) 
    linkObj.href = 'contactus.php';
else
    linkObj.href = '#';
于 2012-08-31T23:36:36.623 回答