请先引入jquery库
以下是代码:
[code lang=”js”]
jQuery.cookie = function(name, value, options) {
if (typeof value != ‘undefined’) { // name and value given, set cookie
options = options || {};
if (value === null) {
value = ”;
options.expires = – 1;
}
var expires = ”;
if (options.expires && (typeof options.expires == ‘number’ || options.expires.toUTCString)) {
var date;
if (typeof options.expires == ‘number’) {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = ‘; expires=’ + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// CAUTION: Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason…
var path = options.path ? ‘; path=’ + (options.path) : ”;
var domain = options.domain ? ‘; domain=’ + (options.domain) : ”;
var secure = options.secure ? ‘; secure’: ”;
document.cookie = [name, ‘=’, encodeURIComponent(value), expires, path, domain, secure].join(”);
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != ”) {
var cookies = document.cookie.split(‘;’);
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
var options = {
expires : 1
}
if ($.cookie('viewTimes') == null) {
alert("您是第1次访问本站")
$.cookie('viewTimes', '1', options);
} else {
var cookie = parseInt($.cookie('viewTimes')) + 1;
alert("这是您第" + cookie + "次访问本站");
$.cookie('viewTimes', cookie, options);
}
[/code]
功能的实现利用了Jquery.cookie来更加便捷地操作cookie。
有关cookie可以参考《细说cookie》http://www.cnblogs.com/fish-li/archive/2011/07/03/2096903.html ,我就不重复说cookie的一些事儿了。
原理很简单,就是给cookie设置一个viewTimes的值,通过这个值来判断其是否是第一次访问本站。
注意:cookie需要服务环境的支持。