乐闻世界logo
搜索文章和话题

How do I set a cookie to expire after 1 minute or 30 seconds in Jquery?

1个答案

1

Setting cookies in jQuery typically requires additional libraries because native jQuery does not support direct cookie manipulation. We commonly use the jquery.cookie plugin to simplify this process. First, ensure that you have included the jQuery library and the jquery.cookie plugin.

To set a cookie to expire after 1 minute or 30 seconds, use the $.cookie function with the expires option, which defines the cookie's lifespan in days. For minutes or seconds, calculate the expiration time using the Date object.

javascript
// First, ensure the jQuery library and `jquery.cookie` plugin are included // <script src="path/to/jquery.js"></script> // <script src="path/to/jquery.cookie.js"></script> $(document).ready(function() { var date = new Date(); date.setTime(date.getTime() + (1 * 60 * 1000)); // Time one minute from now $.cookie('cookie_name', 'cookie_value', { expires: date }); });
javascript
$(document).ready(function() { var date = new Date(); date.setTime(date.getTime() + (30 * 1000)); // Time 30 seconds from now $.cookie('cookie_name', 'cookie_value', { expires: date }); });

Important Note

When using the expires option, passing a Date object ensures millisecond precision, allowing specific expiration times like 30 seconds or 1 minute. Additionally, verify that jQuery and the jquery.cookie plugin are loaded before setting cookies; otherwise, the code will fail. This approach enables flexible cookie expiration for temporary data storage scenarios.

2024年8月12日 14:28 回复

你的答案