Javascript 试图在
我试图从日期列表中找到下一个/最近的日期,然后向其中添加一个类,并在其他位置显示该项目Javascript 试图在,javascript,jquery,Javascript,Jquery,我试图从日期列表中找到下一个/最近的日期,然后向其中添加一个类,并在其他位置显示该项目 <ul class="locations"> <li> <span class="date">01-Jun-2015</span> <span class="location">London</span> </li> <li> <spa
<ul class="locations">
<li>
<span class="date">01-Jun-2015</span>
<span class="location">London</span>
</li>
<li>
<span class="date">15-Jun-2015</span>
<span class="location">Paris</span>
</li>
<li>
<span class="date">03-Jul-2015</span>
<span class="location">Berlin</span>
</li>
<li>
<span class="date">16-Jun-2015</span>
<span class="location">Milan</span>
</li>
<li>
<span class="date">20-Jul-2015</span>
<span class="location">Madrid</span>
</li>
<li>
<span class="date">07-Aug-2015</span>
<span class="location">Lisbon</span>
</li>
</ul>
<p class="next-date">
Next date and location:
</p>
有人能帮我指出正确的方向吗?我编写了一个自定义排序函数,以便在下一个日期对壁橱进行排序
dates.sort(function(x, y) {
if (x[0]-Date.now() < 0) {
return 1;
}
if (x[0]-Date.now() < y[0]-Date.now()) {
return -1;
}
if (x[0]-Date.now() > y[0]-Date.now()) {
return 1;
}
return 0;
});
尝试使用日期进行比较:
$function{
var now=new Date.getTime;//获取当前时间
var li、diff、sp、tmp;
$'span.date'。每个函数{//在所有日期中循环
sp=$this;
如果!li{//第一次
li=sp.closest'li';//获取日期的父项
diff=Math.absnow-new Datesp.text.getTime;//获取差异
回来
}
tmp=Math.absnow-new Datesp.text.getTime;
如果tmp我想您会同意jQuery,因为您的问题被标记为这样。您可以使用两个内置函数(如和)找到最接近今天的未来日期。请查看脚本中的注释以了解有关代码的更多信息 变量$locations=$.locations; //今天的日期以毫秒为单位 var tsToday=new Date.getTime; //使用.map创建时间戳数组 var allDatesTimestamp=$locations.find.date.mapfunction{ //以毫秒为单位将文本转换为日期 var ts=新日期$this.text.getTime; //仅返回大于今天的时间戳 //并对它们进行排序,以获得最小/最近的时间戳作为第一个数组项 如果ts>tsToday{ 返回ts; } }.get.sort; //查找所有.date元素并过滤掉 var$elem=$locations.find.date.filterfunction{ //筛选出日期等于数组中第一项的日期,因为这是最接近的日期 返回新日期$this.text.getTime==allDatesTimestamp[0] //返回舍入元素 //如果需要,添加一个类以突出显示它 }.closestli.addClassnearest; //休息很简单;查找并显示。 美元。下一个日期 .appendDate:+$elem.find.date.text .appendLocation:+$elem.find.location.text; .地点。最近的{ 颜色:绿色; 字号:1.5em; } 2015年6月1日 伦敦 2015年6月15日 巴黎 2015年7月3日 柏林 2015年6月16日 米兰 2015年7月20日 马德里 2015年8月7日 里斯本
下次日期和地点:
最接近哪个日期?将每个跨度内部文本转换为日期。然后对每个日期比较其与当前日期的距离,并选择最小距离。将类添加到相关span。我认为这是我首选的方法,谢谢。评论有很大的帮助!