我想每次引用页面时都增加一个cookie值,即使该页面是从缓存中加载的。实现此目的的“最佳”或最简洁的方法是什么?
从http://www.quirksmode.org/js/cookies.html#script被盗
function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toUTCString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; 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,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
使用它:
var oldCount = parseInt(readCookie('hitCount'), 10) || 0; createCookie('hitCount', oldCount + 1, 7);
如评论中指出的那样,由于cookie被存储并作为字符串返回,因此您应该将其强制转换为int。使用foo++或++foo会为您实际投放,但更确切地知道您正在使用的是更安全的方法:
foo++
++foo
var x = "5"; // x = "5" (string) x += 1; // x = "51" (string!) x += 5; // x = "515" (string!) ++x; // x = 516 (number)