0

初めてhtmlがロードされ、テキストがYesとして表示され、2回目にリロードまたはキャッシュからロードされると、他のテキストNOが表示されます。

4

2 に答える 2

1

jQueryを使用しているので、jQueryCookieプラグインを使用するのが最も簡単なようです。

// 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 に答える