简体   繁体   English

Javascript在按钮点击时设置cookie到期时间

[英]Javascript set cookie expire time on button click

onClick="javascript:document.cookie='n=1'"

Im new in javascript 我是javascript新手

I have a btn click will set cookie, how can I set expire time 1 hour on this cookie? 我有一个btn点击将设置cookie,我如何设置这个cookie 1小时的到期时间?

When you write the cookie to the browser, you need to specify an expiration date or a max age. 将cookie写入浏览器时,需要指定过期日期或最大年龄。 However, note that max-age is ignored by Interent Explorer 8 and below. 但请注意,Interent Explorer 8及以下版本会忽略max-age。 So if you're expecting to get usage from that browser, you can just rely on expires. 因此,如果您希望从该浏览器获得使用,您可以依赖过期。

Example: 例:

<script type="text/javascript">
function setMyCookie() {
   var now = new Date();
   var expires = new Date(now.setTime(now.getTime() + 60 * 60 * 1000)); //Expire in one hour
   document.cookie = 'n=1;path=/;expires='+expires.toGMTString()+';';
}
</script>

And your button can call this function like so: 你的按钮可以像这样调用这个函数:

<input type="button" onclick="setMyCookie();">Set Cookie</input>

Note that I've also included the path to indicate that this cookie is site-wide. 请注意,我还包含了指示此cookie在站点范围内的路径。

You can read more about expiring cookies with the date or max-age here: http://mrcoles.com/blog/cookies-max-age-vs-expires/ 您可以在此处阅读有关日期或最大年龄的过期Cookie的更多信息: http//mrcoles.com/blog/cookies-max-age-vs-expires/

You can do: 你可以做:

onClick="setupCookie();"

function setupCookie() {
    document.cookie = "n=1";
    setTimeout(function() {
        document.cookie = "n=0";
    }, 3600000); // 1 hour
}

On click you can call some javascript function and while creating cookie itself you can set expire time please refer this 点击你可以调用一些javascript函数,并在创建cookie本身时你可以设置过期时间请参考这个

javascript set cookie with expire time javascript设置cookie与过期时间

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

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