将Cookie设置为功能,然后检查页面重新加载并执行某些操作 [英] Set cookie in a funtion, then check on page reload and do something

查看:57
本文介绍了将Cookie设置为功能,然后检查页面重新加载并执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数末尾并重新加载页面时为cookie设置一个值,请检查该代码是否存在.像这样:

I would like to set a value for a cookie at the end of a function and on page reload, check for the existence of that code. Something like:

function onObjectDrag() {
// save code
$.cookie("saved", 1);
location.reload();
}

然后,刷新页面时,检查该cookie是否存在,如果存在,请执行某些操作,然后删除该cookie.如果没有,则什么也不要做.

Then when the page is refreshed, check if that cookie exists and if so, do something then delete the cookie. If not, don't do anything.

推荐答案

在没有任何条件的情况下或将cookie设置为零后,请勿调用 onObjectDrag()

Do not call onObjectDrag() without any condition or after you set the cookie to zero or else you will end up with a recursion.

function onObjectDrag() {
    setCookie('saved', 1, 100);
    location.reload();
}

$( document ).ready(function() {
    var x = getCookie('saved');
    if (x == 1) {
        //do something
        setCookie('saved', 0, 100);
    }
});

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

这篇关于将Cookie设置为功能,然后检查页面重新加载并执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆