使用jQuery在1月或12月进行切换

时间:2014-05-22 06:12:48

标签: jquery toggle

编写了一个用于切换月份和年份的代码,就像在右下角点击它时在Windows时钟中看到的那样。我只是想用红色突出显示上半部分。没有压延机。

enter image description here

我已经实现了所有这一切,但存在故障。当你去往未来几个月它改变12月的年份。它应该改变1月份的年份。回去的时候一样。您可以在此处查看实时示例... Fiddle

这是我的jQuery代码:

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

var d = new Date();
var $m = d.getMonth() + 1;
var $y = d.getFullYear();


$('.history-months').click(function () {
    var month_num = $('.months').attr('month-count');
    var year_num = $('.years').text();
    var history_month = parseFloat(month_num) - 1;
    $('.months').attr("month-count", history_month);
    $('.months').text($months[history_month]);
    if (month_num < 3) {
        $('.months').attr("month-count", 13);
        var history_year = parseFloat(year_num) - 1;
        $('.years').text(history_year);
    }
});
$('.future-months').click(function () {
    var month_num = $('.months').attr('month-count');
    var year_num = $('.years').text();
    var future_month = parseFloat(month_num) + 1;
    $('.months').attr("month-count", future_month);
    $('.months').text($months[future_month]);
    if (month_num > 10) {
        $('.months').attr("month-count", 0);
        var history_year = parseFloat(year_num) + 1;
        $('.years').text(history_year);
    }
});

$('.months').text($months[$m]).attr('month-count', $m);
$('.years').text($y);

这是HTML:

<a href="#" class="history-months">&LT;</a>

<span class="months-years">
    <span class="months"></span>
    <span class="years"></span>
</span>

<a href="#" class="future-months">&GT;</a>

有什么想法吗?

由于

欧麦

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案:p

我认为我也应该与世界分享:)

稍微修改一下我的情况:

$('.future-months').click(function() {
    var month_num = $('.months').attr('month-count');
    var year_num = $('.years').text();
    var future_month = parseFloat(month_num) + 1;
    if (future_month > 12) {
         future_month = 1;
         year_num = parseFloat(year_num) + 1;
    }
    $('.months').attr("month-count", future_month);
    $('.months').text($months[future_month]);
    $('.years').text(year_num);
});

$('.history-months').click(function() {
    var month_num = $('.months').attr('month-count');
    var year_num = $('.years').text();
    var history_month = parseFloat(month_num) - 1;
    if (history_month < 1) {
         history_month = 12;
         year_num = parseFloat(year_num) - 1;
    }
    $('.months').attr("month-count", history_month);
    $('.months').text($months[history_month]);
    $('.years').text(year_num);
});

希望它对其他人有所帮助:)。

欧麦