Cookie添加按钮命中

dvl*_*den 3 javascript cookies jquery onclick javascript-events

我在添加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>
Run Code Online (Sandbox Code Playgroud)

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();
});
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*ill 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 });
});
Run Code Online (Sandbox Code Playgroud)