<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery.min.js"></script> <script src="js/jquery.cookie.js"></script> <script> $(document).ready(function() { //所创建的cookie有效期默认到用户关闭浏览器为止 $.cookie('the_cookie', '五颜六色千变万化'); //创建一个cookie并设置 cookie的有效路径: $.cookie('the_cookie_expires_07', '世界是座魔方大厦', { expires: 7 }); //读取cookie var value = $.cookie('the_cookie'); var value_07 = $.cookie('the_cookie_expires_07'); $('p').html('读取cookie的值:' + value + '<br />' + '读取cookie存在7天的值:' + value_07); }); //清除所有cookie函数 function clearAllCookie() { var keys = document.cookie.match(/[^ =;]+(?=\=)/g); if(keys) { for(var i = keys.length; i--;) document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString() } }
/**清楚指定cookie**/ $("#logoutId").click(function () { //清除所有cookie函数 var keys = document.cookie.match(/[^ =;]+(?=\=)/g); // console.log(keys); // alert(keys),name,items if(keys) { for(var i = keys.length; i--;){ // console.log(keys[i]); // alert(keys[i]) if(keys[i]=="items" || keys[i]=="name"){ document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString() } } } });
</script> <title></title> </head> <body> <p></p> <button οnclick="clearAllCookie();">清除所有的cookie</button> </body> </html> 在浏览器中写入cookie
当点击清除所有cookie的按钮后: