使用moment.js我编写了一个脚本,该脚本遍历事件列表并隐藏那些在6个多小时前开始并被认为已完成的事件。
var x=document.getElementsByClassName("event");
for (var i=0;i<x.length;i++) {
var starttime = moment((x[i].getElementsByClassName("start")[0].childNodes[0].nodeValue), 'YYYY-MM-DD HH:mm');
var cutoff = moment().subtract(6, 'hours').format('YYYY-MM-DD HH:mm');
if (starttime.isBefore(cutoff)) {
var expired=(x[i].getElementsByClassName("event-container")[0]);
expired.style.display = "none";
}
}
脚本工作正常,但完全隐藏div并不是最好的主意。我想把所有过期的事件包装在一个div中,然后如果你还想查看它们就可以打开。我该怎么做呢?
最终结果如下:
<div class="openclose">
<div class="event">
<div class="event-container">
Old event info goes here
</div>
</div>
<div class="event">
<div class="event-container">
Old event info goes here
</div>
</div>
</div>
<div class="event">
<div class="event-container">
New event info goes here
</div>
</div>
<div class="event">
<div class="event-container">
New event info goes here
</div>
</div>
答案 0 :(得分:1)
用这个替换你的javascript
var oldEvents = document.getElementById("oldEvents");
var x=document.getElementsByClassName("event");
for (var i=0;i<x.length;i++) {
var starttime = moment((x[i].getElementsByClassName("start")[0].childNodes[0].nodeValue), 'YYYY-MM-DD HH:mm');
var cutoff = moment().subtract(6, 'hours').format('YYYY-MM-DD HH:mm');
if (starttime.isBefore(cutoff)) {
oldEvents.appendChild(x[i]);
}
}
这会将event
div附加到oldEvents
div appendChild()
你可以在你的html中使用一个空的div来填充时间。
<div class="openclose" id="oldEvents">
<div class="event">
<div class="event-container">
Old event info goes here
</div>
</div>
<div class="event">
<div class="event-container">
Old event info goes here
</div>
</div>
</div>
<div class="event">
<div class="event-container">
New event info goes here
</div>
</div>
<div class="event">
<div class="event-container">
New event info goes here
</div>
</div>
答案 1 :(得分:0)
我想如果你destroy过期的元素会更好。在销毁元素之前,将其附加到div#openclose
var eventDiv = '<div class="event"><div class="event-container">'+expired.innerHTML+'</div></div>';
var opencloseContainer = document.getElementByClassName("openclose");
opencloseContainer.innerHTML += eventDiv;