我有一个日期列表,我想抓住最新的日期,然后在H2中显示它(特别是span.lastupdated标签)。
<h2>Specials (Updated <span class="lastUpdated"></span>)</h2>
<ul class="items">
<li>June 1, 2017</li>
<li>August 1, 2017</li>
<li>September 27, 2017</li>
</ul>
使用jquery完成此任务的最佳方法是什么?
答案 0 :(得分:0)
如果您将它们变为日期对象,则可以直接将它们与<
:
var date = new Date('Jan 1 1980');
var dateString = '';
$('.items li').each(function(num, elem) {
var thisDate = new Date($(elem).text());
if (thisDate > date) {
date = thisDate;
dateString = $(elem).text();
}
});
$('.lastUpdated').text(dateString);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Specials (Updated <span class="lastUpdated"></span>)</h2>
<ul class="items">
<li>June 1, 2017</li>
<li>August 1, 2017</li>
<li>September 27, 2017</li>
</ul>
&#13;
答案 1 :(得分:0)
你可以尝试
<script>
$(document).ready(function(){
var listDates = [];
$('.items li').each(function (i) {
var listDateValue = $(this).text();
listDates.push(listDateValue);
});
var formattedDates = listDates.map(function(x) { return new Date(x); }) //contains the list of dates available within each item in your ul element.
var maxDate = new Date(Math.max.apply(null,formattedDates));
$(".lastUpdated").html(maxDate);
});
</script>
答案 2 :(得分:0)
你可以在一个循环中完成所有事情:
var mostRecent = null;
var position = null;
var items = $('.items').children();
items.each(function(index, element) {
var temp = new Date($(element).text());
if (!mostRecent || temp > mostRecent) {
mostRecent = temp;
position = index;
}
});
if (position != null)
$('span.lastUpdated').text($(items[position]).text());