0

第一次加载 html 并将文本显示为是,第二次从缓存重新加载或加载时它应该显示一些其他文本 NO。

4

2 回答 2

1

当您使用 jQuery 时,使用jQuery Cookie 插件似乎最简单:

// assigns the value returned by the cookie to the variable,
// if no cookie, or no value, is returned, the string is assigned instead.
var cookieValue = $.cookie('firstVisit') || 'Yes';

// if there's no cookie, then a cookie is set.
if (!$.cookie('firstVisit')) {
    $.cookie('firstVisit', 'No', {
        expires: 7 // expires in 7 days, adjust to taste.
    });
}

$('#firstVisit').text(cookieValue);​

JS 小提琴演示

上面的代码更新得更整洁,重复更少:

// if the cookie is not set, the cookieVal variable is falsey
var cookieVal = $.cookie('firstVisit'),
    // creating a reference to the relevant div
    div = $('#firstVisit');

// if the cookieVal evaluates to false the cookie is set,
// and the text of the div is 'Yes'
if (!cookieVal) {
    $.cookie('firstVisit', 'No');
    div.text('Yes');
}
// otherwise...
else {
    // text of the div is equal to the value returned from the cookie
    div.text(cookieVal);
}​

JS 小提琴演示

于 2012-07-20T21:22:56.363 回答
0

您可以使用 cookie 来识别回访者:

<html>
<body>

<script language="javascript">

// sets a cookie with a certain name, value and optional expiration in days
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;
}

// retrieves the value of a cookie of a certain name (or returns undefined)
function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) return unescape(y);
    }
}

// if the cookie was set, then the user has been here already
if (getCookie("visited") == "true") {
    document.write("NO");
} else {
    // otherwise, set the cookie and assume the user has not been here before
    setCookie("visited", "true");
    document.write("YES");  
}

</script>

</body>
</html>

见:http ://en.wikipedia.org/wiki/HTTP_cookie

于 2012-07-20T21:20:34.497 回答