Adding a class based on current day of the week

心不动则不痛 提交于 2021-02-11 03:00:26

问题


I've got a bunch of tabbed divs on a page for each day of the week, which are being shown/hidden with jQuery when clicked.

The class "first", added manually to whatever tab I want, tells the page which div to show when the user first lands there.

At the moment it is set to the Monday div.

How would I go about setting this up so that jQuery can add the class dynamically to the actual current day's div instead of hard coding it?

Divs are set up like this (with Monday being currently selected):

 <div id="sh-MON" class="daily-Sched first">
 <div id="sh-TUE" class="daily-Sched">
 <div id="sh-WED" class="daily-Sched">

 etc

I know it's something to do with "eq" and have tried this below but it doesn't work. I can't see how it would either?

 $('.daily-Sched:eq(' + new Date().getDay() + ')').addClass('first');

Any help greatly apppreciated.

Cheers!


回答1:


var d = new Date();
var n = d.getDay();

n = n > 0 ? n - 1 : 6; // zero is sunday, not monday in javascript

$('.daily-Sched').eq(n).addClass('first');

FIDDLE



来源:https://stackoverflow.com/questions/24599263/adding-a-class-based-on-current-day-of-the-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!