如果你想在JavaScript中創建和檢查cookie,那麼我可以用3-4個月前寫的一些代碼來幫助你。
如果你想要這個,那麼你去這裏
走在HTML網頁上的按鈕,並調用它的onclick功能的JavaScript函數「checkCookie()」。
<input type="button" value="Click Me" onclick="checkCookie()" />
現在轉到頭部並在那裏定義checkCookie()方法。
function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") {
alert("Welcome again " + username);
}
else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookie("username", username, 365);
}
}
}
現在,如果你的瀏覽器都可以節省你在文本框中中的cookie中輸入名稱,然後上面的方法會告訴你一個警告說「歡迎再次‘您輸入的名字。’」
讓我們定義getCookie()方法。
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
現在定義setCookie()方法。
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires="
+ exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
對於整個提示您可以訪問到我這裏寫的文章,Check and Create Cookie in Javascript
也許你使用域使用和不使用WWW – yAnTar 2012-04-06 19:18:32