2014-05-22 62 views
0

已經編寫了一個代碼,用於切換幾個月和幾年,就像您在Windows時鐘中看到的,當您在右下角點擊它時。我只想以紅色突出顯示上半部分。它下面沒有日曆。使用jQuery切換一年或十二月的年份

enter image description here

我已經實現了這一切,但有毛刺。當你走向未來的幾個月時,它會在十二月份改變這一年。它應該改變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> 

任何想法?

感謝

奧馬爾

回答

0

好吧發現自己的解決方案:對

我想我應該與世界以及:)

份額僅爲編輯我的情況有點:

$('.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); 
}); 

希望這會對其他人有所幫助:)

Omer