按钮单击6次时设置cookie并禁用单击

时间:2013-10-20 12:45:59

标签: jquery cookies limit

我试图按一下按钮限制只点击六次,然后让它无法点击30分钟,即使你重新加载页面也必须禁用,但是30分钟后再次显示按钮没有重新加载页面,这是否可能?我需要帮助。

以下是代码:

(function(){
    var click_counter = 0;
    jQuery('.controls_next').on('click', function(event){
        event.preventDefault();
        var el = jQuery(this);
        click_counter += 1;
        if (!el.hasClass('')){
            // should be activated
        };
        if (click_counter >= 6){
            // deactivate
            el.addClass('disabled');
            var date = new Date();
            var minutes = 01;
            date.setTime(date.getTime() + (minutes * 60 * 1000));
            $.cookie("skipSongCookie", { expires: date });
        };
    });
})();

2 个答案:

答案 0 :(得分:0)

您可以设置Cookie并更改值:

function setCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

答案 1 :(得分:0)

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function checkCookie(name, days)
{
    var value = readCookie(name);
    if (value === null) {
        createCookie(name, 1, days);
    } else {
        value += 1;
        createCookie(name, value + 1, days)
    }
    return value;
}
$(function() {
    var name = 'cookie_name';
    var days = 365;
    $('.controls_next').click(function() {
        var click_counter = checkCookie(name, days);
        if(click_counter >= 6){
            $('.controls_next').attr('disabled', 'disabled');
            // or $('.controls_next').addClass('disabled');
        }

    });
});