我们有2个列表元素。
来自:(必须显示本月至未来4个月),如
<li>October 2017</li>
<li>November 2017</li>
<li>December 2017</li>
<li>January 2018</li>
<li>Febraury 2018</li>
要:(必须显示从本月到过去4个月的1年),如
<li>June 2018</li>
<li>July 2018</li>
<li>August 2018</li>
<li>September 2018</li>
<li>October 2018</li>
我们是否可以使用Javascript或Jquery显示它。
JS:
getFullMonth() {
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var n = month[d.getMonth()];
document.getElementById("fromDate").innerHTML = n;
}
答案 0 :(得分:2)
要实现此目的,您可以使用基于当前月份的for
循环并递增每次迭代,并将li
与目标月份相关联添加到相关ul
,如下所示:
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var currentMonth = new Date().getMonth();
for (var i = 0; i < 5; i++) {
$('.from').append(`<li>${months[(currentMonth + i) % months.length]}</li>`);
$('.to').append(`<li>${months[(currentMonth + i + 8) % months.length]}</li>`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="from"></ul>
<ul class="to"></ul>
答案 1 :(得分:0)
我更喜欢使用moment library进行日期操作,它会让事情变得更好。
所以你需要打印未来5个月的清单,包括当前的清单。然后,您需要第二个相应的列表,前面是1 year - 4 months
,或者+ 8 months
是为了简单。
for (var i = 0; i<5; i++) {
var dt = moment().add(i, 'months');
$('<li />').text(dt.format('MMMM YYYY')).appendTo('#current')
dt.add(8, 'months');
$('<li />').text(dt.format('MMMM YYYY')).appendTo('#advanced')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<ul id="current"></ul>
<ul id="advanced"></ul>
答案 2 :(得分:-1)
你可以这样做:
for (var i = 0; i<5; i++) {
var dt = moment().add(i, 'months');
$('<li />').text(dt.format('MMMM YYYY')).appendTo('#current')
dt.add(8, 'months');
$('<li />').text(dt.format('MMMM YYYY')).appendTo('#advanced')
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<ul id="current"></ul>
<ul id="advanced"></ul>
&#13;