当前日期向前推4天,向后台推4天(当前日期标注为红色),渲染到页面并添加点击事件

一、效果图如下

在这里插入图片描述

二、引入jq

<script src="./js/jquery-3.5.1.min.js"></script>

三、页面样式结构

//样式
<style>
  .action{
    color: red;
  }
</style>

//结构
<h4>当前时间向前推4天,向后台推4天(当前日期标注为红色)</h4>
<div id="dataDom"></div>

四、js



  // 时间转换(标准时间转换成yyyy-mm-dd格式)
  function formatDateTime (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    // return y + '-' + m + '-' + d+' '+h+':'+minute;
    return y + '-' + m + '-' + d
  };
  
  
  //获取指定日期的相差多少天的日期
  // 指定日期--dateParameter格式:("2022-04-01或者2022/04/01")
  // 相差多少天--num为数字
  // 向前推 type为1;向后推 type为2
  function pushByTransDate(dateParameter, num, type) {
    var translateDate = "", dateString = "", monthString = "", dayString = "";
    translateDate = dateParameter.replace("-", "/").replace("-", "/"); 
    var newDate = new Date(translateDate);
    newDate = newDate.valueOf();
    if(type == 1){
      newDate = newDate - num * 24 * 60 * 60 * 1000;//向前推
    }else{
      newDate = newDate + num * 24 * 60 * 60 * 1000;//向后推
    }
    
    newDate = new Date(newDate);
    //如果月份长度少于2,则前加 0 补位
    if ((newDate.getMonth() + 1).toString().length == 1) {
      monthString = 0 + "" + (newDate.getMonth() + 1).toString();
    } else {
      monthString = (newDate.getMonth() + 1).toString();
    }
    //如果天数长度少于2,则前加 0 补位
    if (newDate.getDate().toString().length == 1) {
      dayString = 0 + "" + newDate.getDate().toString();
    } else {
      dayString = newDate.getDate().toString();
    }
    dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString;
    return dateString;
  };
  


  // 获取当前时间
  let dateList = []
  let currentDate=''
  let newDate = new Date() //当前时间
  currentDate = formatDateTime(newDate);//当前时间-格式转换
  // currentDate = "2022-04-02" // 指定日期

  // 向前推4天
  for(var a=4;a>0;a--){
    let nTime = pushByTransDate(currentDate, a, 1);
    dateList.push(nTime)
  }
  // 当前时间
  dateList.push(currentDate)
  // 向后推4天
  for(var b=1;b<=4;b++){
    let mTime = pushByTransDate(currentDate, b, 2);
    dateList.push(mTime)
  }

  // 渲染到页面
  let dateListHtml=''
  dateList.forEach(item => {
    if(item == currentDate){
      dateListHtml +=`<p class="action" onClick="handleDateClick('${item}')">${item}</p>`
    } else {
      dateListHtml +=`<p>${item}</p>`
    }
    
  })
  $("#dataDom").html(dateListHtml)

  // 当前日期点击事件
  function handleDateClick(itm){
    console.log("点击了当前日期",itm);
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值