Setting and Unsetting Cookies with jQuery
To manipulate cookies using jQuery, the recommended approach is no longer using the jQuery Cookie plugin. Instead, it's advised to use the standalone js-cookie library, available at https://github.com/js-cookie/js-cookie.
Setting a Cookie
To set a cookie with js-cookie:
Cookies.set('name', 'value');
For instance, to set a cookie named "test" with a value of 1:
Cookies.set('test', 1);
Unsetting a Cookie
To delete a cookie with js-cookie:
Cookies.remove('name');
Using the previous example, to delete the "test" cookie:
Cookies.remove('test');
Setting Custom Options
To set custom options for a cookie, such as expiration time or domain, pass an object as the third argument:
Cookies.set('test', 1, { expires: 10, // Expires in 10 days path: '/', // The path attribute of the cookie domain: 'jquery.com', // The domain attribute of the cookie secure: true // The secure attribute of the cookie });
Reading Cookie Values
To retrieve the value of a cookie:
var cookieValue = Cookies.get('name');
For example, to retrieve the value of the "test" cookie:
var testValue = Cookies.get('test');
The above is the detailed content of How Can I Set, Unset, and Manage Cookies with js-cookie?. For more information, please follow other related articles on the PHP Chinese website!