3

我在添加 cookie 时遇到问题。阅读几个答案,但如果您以前从未与他们合作过,就很难理解。

如果有人单击指定的按钮,我基本上想要的是添加一个 cookie。因此,例如,如果有人单击“喜欢按钮”,无论他前进/后退还是刷新页面,隐藏的内容都会显示出来,并且 cookie 会在几天后被删除。

我用来隐藏内容的内容如下:

HTML:

<div id="fd">
    <p>Button from below will become active once you hit like button!</p>
    <div id="get-it">
        <a class="button"><img src="img/get-button.png"></a>
    </div>
</div>
<div id='feedback' style='display:none'></div>

javascript:

FB.Event.subscribe('edge.create', function (response) {
    $('#feedback').fadeIn().html('<p>Thank you. You may proceed now!</p><br/><div id="get-it"><a class="button2" href="pick.html"><img src="img/get-button.png"></a></div>');
    $('#fd').fadeOut();
});

但是,如果我在内容页面上点击刷新或返回/前进,它将再次被隐藏。这就是我想在按钮点击时添加 cookie 的原因。谁能给我一些解释或示例代码?

4

2 回答 2

13

我建议使用jQuery-cookie 插件。以下是一些使用示例:

// Create a cookie
$.cookie('the_cookie', 'the_value');

// Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });

// Read a cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null

// EDIT
// Attaching to a button click (jQuery 1.7+) and set cookie
$("#idOfYourButton").on("click", function () {
    $.cookie('the_cookie', 'the_value', { expires: 7 });
});

// Attaching to a button click (jQuery < 1.7) and set cookie
$("#idOfYourButton").click(function () {
    $.cookie('the_cookie', 'the_value', { expires: 7 });
});

您还需要检查 cookie 是否存在(在重新加载浏览器时:

if ($.cookie('the_cookie')) {
    // Apply rule you want to apply
    $('.ClassToSelect').css("display", "none");
}
于 2012-04-27T17:31:11.897 回答
3

我建议您使用localStorage而不是 cookie 。

于 2012-04-27T17:28:56.897 回答