簡體   English   中英

使用 jquery 增加或減少值

[英]Increase or decrease value using jquery

我有一個 javascript 變量,它是當前日期的天數。

我想讓用戶通過單擊按鈕轉到上一個日期。

這是小提琴

嘗試谷歌搜索,但我不明白或任何幫助我。

我可以通過在 day 變量中給出-1來減少一天。 但我不知道如何在每次點擊時減少它。

有人幫助我如何減少和增加點擊這些按鈕的日期?

提前致謝。

您的代碼中有幾個問題。 主要的一個是您在每次單擊當前日期的按鈕時創建一個新的日期對象。 這就是為什么你每次都得到相同的結果。

如果您只想在日期中添加或刪除一天,您可以這樣做:

var currentDate = new Date();    
$('button').click(function() {
    var add = $(this).hasClass('increase_date') ? 1 : -1;
    currentDate.setDate(currentDate.getDate()+add);
    $('.display_date').html(currentDate);    
})

http://jsfiddle.net/3VQZy/

將您的當前日期存儲在一個global variable並在其上使用-= operator並使用當前值將其減一。

像這樣的http://jsfiddle.net/SYRDR/2/我只展示了如何減少它,你必須添加更多的條件來正確格式化日期

演示: http : //jsfiddle.net/SYRDR/14/

$(document).ready(function() {
        showDate(0);
        $('.decrease_date').click(function() {
            showDate(-1);        
        });
        $('.increase_date').click(function() {
            showDate(1);        
        });
    })

    function showDate(change)
    {
        var current_date;    
        if(change == 0)
        {
            current_date = new Date();
        }
        else
        {
            current_date = new Date($('.display_date').html());
        }        
            var year = current_date.getFullYear();
            var month = "0" + (current_date.getMonth() + 1);
            var day = current_date.getDate();

        if(change == -1)
        {
            day = day - 1;
        }    
        if(change == 1)
        {
            day = day + 1;
        }
            var start_date2 = year + "-" + month + "-" + day;        
            $('.display_date').html(start_date2);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM