从一系列月份中获取当前月份

时间:2016-05-30 12:24:16

标签: jquery arrays date swiper

我有一个基本上如下的数组:

这个数组是动态的,让我们说它已经进入了几个月:

  

"五月"" 6月"

也可以这样:

  

" May"," June"," July" ...

我需要能够在当前月份的滑块中进行设置。我一直在这样做:

swiper.slideTo(new DateTime().getMonth()); // fetches current month index ( if May it is 5 since indexation goes from 0)

我的幻灯片看起来像这样:

<div class="swiper-wrapper">
    <div class="swiper-slide active"><h3>January</h3></div>
    <div class="swiper-slide active"><h3>February</h3></div>
    <div class="swiper-slide active"><h3>March</h3></div>
    <div class="swiper-slide active"><h3>April</h3></div>
    <div class="swiper-slide active"><h3>May</h3></div>
    <div class="swiper-slide active"><h3>June</h3></div>
    <div class="swiper-slide active"><h3>July</h3></div>
    <div class="swiper-slide active"><h3>August</h3></div>
    <div class="swiper-slide active"><h3>September</h3></div>
    <div class="swiper-slide active"><h3>October</h3></div>
    <div class="swiper-slide active"><h3>November</h3></div>
    <div class="swiper-slide active"><h3>December</h3></div>
</div>

swiper中的指数也从0到11,所以很容易将当前的幻灯片设置为当月。现在的问题是,如果阵列从1月开始没有开始,我怎么能设置当前月份,但是我仍然可以将当前幻灯片设置为正确的月份...例如,如果幻灯片开始从五月到七月...如果当前月份是六月,我希望能够将当前幻灯片设置为六月...

我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

使用jQuery

非常容易
Subject

JSFiddle

答案 1 :(得分:0)

我不确定Javascript是否具有开箱即用功能,可将月份索引转换为字符串。但如果没有,最简单的方法是保留一个包含变量中所有月份名称的固定数组,并查找当月的索引,从而得到当月的名称。然后,您可以在幻灯片数组上使用.indexOf来获取将滑块设置为的索引。

可能是这样的:

var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

function getSliderIndex(slides) {
    var currentMonthName = MONTHS[new Date().getMonth()];
    return slides.indexOf(currentMonthName)
}

答案 2 :(得分:0)

如果你要给每个div一些东西来识别月份(这可能是一个CSS类,一个ID,一个数据属性......)你可以遍历DIVS并选择你想要的那个。

下面是一个带有自定义数据属性的示例:

<div class="swiper-wrapper">
   <div class="swiper-slide active" data-month="0"><h3>January</h3></div>
   <div class="swiper-slide active" data-month="1"><h3>February</h3></div>
   ...
   <div class="swiper-slide active" data-month="11"><h3>December</h3></div>
</div>

JS:

var curr_month = new DateTime().getMonth();
$('.swiper-wrapper').children('div').each(function(i) {
    if($(this).data("month") === curr_month){
        swiper.slideTo(i);
    }
});