简体   繁体   English

在首次页面加载时设置Cookie

[英]Set a cookie on first time page load

How can I set a cookie via jQuery cookie ( $.cookie() ) library, only when the page is loaded for the first time? 仅当首次加载页面时,如何才能通过jQuery cookie( $.cookie() )库设置cookie? I currently have a toggle feature, to change the value of the cookie in question upon a click event 我目前具有切换功能,可以在click事件后更改相关Cookie的值

$('.family-filter').click(function() {
    if ($.cookie('ff') == null) {
        $.cookie('ff', 'on', {
            expires: 1,
            path: '/'
        });
    } else {
        $.cookie('ff', null, {
            path: '/'
        });
    }
});

But I need a default value, if none is set already. 但是,如果尚未设置默认值,则需要一个默认值。

Also happy to set it via PHP, but I'd prefer for this case, to do it via Javascript 也很乐意通过PHP进行设置,但在这种情况下,我更喜欢通过Javascript进行设置

In page load you can set this code to check and set cookies 在页面加载中,您可以设置此代码来检查和设置Cookie

<?php

if (!isset($_COOKIE["ff"])) {
    // Expire Time is 30 Days
    $expire = time() + 60 * 60 * 24 * 30;
    setcookie('ff', 'on', $expire);
}

I'm adding a cokkie like so: 我像这样添加一个cokkie:

if (document.cookie.indexOf('visited=true') == -1) {
    var thirtydays = 1000*60*60*24*30;
    var expires = new Date((new Date()).valueOf() +  thirtydays);
    document.cookie = "visited=true;expires=" +  expires.toUTCString();
}

It works fine for me, and you can add some more code inside the if clause if you need something to run while the user it's on his first visit on the website. 它对我来说很好用,如果在用户第一次访问网站时需要运行某些内容,则可以在if子句中添加更多代码。

Well, I decided to implement it this way: 好吧,我决定以这种方式实现它:

if ($.cookie('ff') == null) {
    $.cookie('ff', 'on', {
        expires: 30,
        path: '/'
    });
}

$('.family-filter').click(function() {
    if ($.cookie('ff') == 'off') {
        $.cookie('ff', 'on', {
            expires: 30,
            path: '/'
        });
    } else {
        $.cookie('ff', 'off', {
            path: '/'
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM