javascript Cookie 添加按钮点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10355164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:35:37  来源:igfitidea点击:

Cookie add on button hit

javascriptjquerycookiesonclickjquery-events

提问by dvlden

I have a problem with adding a cookie. Read a couple of answers, but it's hard to understand if you never worked with them before.

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

What I basically want is to add a cookie if someone click on the specified button. So for example, if person clicked on the "like button", hidden content will be revealed no matter if he go forward/back or refresh page and cookie shall be removed after a couple of days.

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

What I used to hide the content is following:

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

HTML:

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:

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

However if I hit refresh or go back/forward on the content page, it will be hidden again. This is reason why I want to add a cookie on button hit. Anyone who can give me some explanations or example code?

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

回答by James Hill

I suggest using the jQuery-cookie plugin. Here's a few examples of usage:

我建议使用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 });
});

You will also need to add a check that the cookie exists (for when the browser is reloaded:

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

if ($.cookie('the_cookie')) {
    // Apply rule you want to apply
    $('.ClassToSelect').css("display", "none");
}

回答by Yusuf X

Instead of cookies, I recommend you use localStorage.

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