如何使用jquery/javascript将类添加到不同的元素中,具体取决于当天

How do I add class using jquery/javascript to different elements depending on what day is it?

本文关键字:元素 取决于 jquery 何使用 javascript 添加      更新时间:2023-09-26

例如,我有4个div。每个div都有特定的日期,当一个类必须添加到其中时,如下所示:


<div class="on-17 on-18"></div>
<div class="on-20"></div>
<div class="on-21"></div>
<div class="on-22"></div>
And I want to add class active on first div, if today is 17th or 18th of current month. Any ideas? Im not saying I need to extract "on-17" to get number 17, it can be manual method, just to check for certain 'on-#'s, in this case 17,18,20,21,22.

For example, if today was 2015-03-17th, it would trigger to add acive class on <div class="on-17 on-18"></div> -> <div class="on-17 on-18 active"></div>

You don't need jQuery to check what date it is. You can use plain Javascript for that.

var today = new Date();
if(today.getDate() === 17) {
  $('.on-17').addClass('active');
}

一个更动态的实现,它总是将类active添加到当前的div:中

var today = new Date();
var dayOfMonth = today.getDate();
$('on-' + dayOfMonth).addClass('active');

如果你每天都有不同编号的课程(比如说你希望每天都有一个不同的颜色):

var today = new Date();
var dayOfMonth = today.getDate();
$('on-' + dayOfMonth).addClass('active-' + dayOfMonth); //Will add the class active-17 on the 17th day of each month, for example