首页 > 解决方案 > JavaScript 日期计算显示/隐藏 Div 日期或逻辑问题?

问题描述

我正在尝试使用 Javascript 在某些日期之间显示 div。有三个div。我不知道是我的逻辑错误还是代码错误。顺便说一句,我正在尝试自学 JavaScript,所以我对预先打包的脚本不感兴趣。提前感谢您的建议!

JavaScript:

<script>
    const date = new Date();
    let offset = 0;
    const threshold = new Date();
    threshold.setMonth(7); //January is 0!
    threshold.setDate(7);
    if (Date.now() > threshold) { 
      offset = 1;
}
var theDate = new Date();
var previous_year = date.getFullYear() - 1 + offset;
var current_year = date.getFullYear() + offset;
var next_year = date.getFullYear() + 1 + offset;

console.log(previous_year);
console.log(current_year);
console.log(next_year);
</script>

<script>
window.setInterval(function(){
  var current = new Date();
  var expiry = new Date("August 01")
  var expiry2 = new Date("February 01")

  if(current.getDate()>=expiry.getDate()){
    $('#one').show();
    $('#two').hide();
    $('#three').hide();
  }

  else if(current.getDate()<=expiry2.getDate()){
     $('#one').hide();   
     $('#two').show();
     $('#three').hide();
   }

  else{
     $('#one').hide();   
     $('#two').hide();
     $('#three').show();
   }
};
$('#one').show(); 
</script>

HTML:

<div id="one" style="display:none">DIV 1 Show >= August 01</div> 

<div id="two" style="display:none">DIV 2 Show <= February 01</div>

<div id="three" style="display:none">DIV 3 Show if February 02 - July 31 </div>

标签: javascripthtml

解决方案


对于初学者,你需要改变这个

}; // <-- semi-colon is not expected here.
$('#one').show(); 

对此

}) // <-- change to parenthesis.
$('#one').show(); 

看起来你那里有一个错字。当我这样做时,“#one”会按预期显示。


推荐阅读