赞
踩
在开发中遇到了如下图需求,要显示一个星期对应的月份和星期计。
已封装了获取月份的方法getDateStr()和获取星期的方法getWeekDateStr()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="listID"></div> </body> <script> //默认日期 var listData = [{ day: "8/19", time: "周一", }, { day: "8/20", time: "周二", }, { day: "8/21", time: "周三", }, { day: "8/22", time: "周四", }, { day: "8/23", time: "周五", }, { day: "8/24", time: "周六", }, { day: "8/25", time: "周日", },]; // 更新数组月份日期 function getDateStr(dayCount) { if (null == dayCount) { dayCount = 0; } var dd = new Date(); dd.setDate(dd.getDate() + dayCount); //设置日期 var m = dd.getMonth() + 1; //获取当前月份的日期 var d = dd.getDate(); if (d < 10) { return m + "/0" + d; } else { return m + "/" + d; } } for (let i = 0; i < 7; i++) { if (i == 0) { listData[i].day = '今天'; } else if (i == 1) { listData[i].day = '明天'; } else if (i == 2) { listData[i].day = '后天'; } else { listData[i].day = getDateStr(i); } } //更新数组星期 function getWeekDateStr(dayCount) { if (null == dayCount) { dayCount = 0; } //更新数组星期 var weekStr = "周" + "日一二三四五六日一二三四五六".charAt(new Date().getDay() + dayCount); return weekStr; } for (let i = 0; i < 7; i++) { listData[i].time = getWeekDateStr(i); } //循环遍历到div中 var listStr = ""; for (var timeStr in listData) { if (timeStr == 0) { listStr += '<ul class="click-list-style">' + '<li>' + listData[timeStr].day + '</li><li class="order-mid-left-text" >' + listData[timeStr].time + '</li>' + '</ul>'; } else { listStr += '<ul>' + '<li>' + listData[timeStr].day + '</li><li class="order-mid-left-text" >' + listData[timeStr].time + '</li>' + '</ul>'; } } document.getElementById("listID").innerHTML = listStr; </script> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。