讀者可以將下面代碼復(fù)制到一個(gè)html文件試試效果;html的pre標(biāo)簽未兩種js實(shí)現(xiàn)的方式
代碼如下:
1.第一種:使用jQuery的cookie庫
例子就是現(xiàn)在正在使用的js,相關(guān)代碼如下:
$(document).ready(function () {
var adCookie=$.cookie("docCookie");
//如果本地沒有cookie,將詞條cookie寫入本地
if(adCookie!="adDocCookie"){
$("#wapDocCookie").show();
}
//如果本地存在詞條cookie,不顯示浮層
if(adCookie=="adDocCookie"){
$("#wapDocCookie").hide();
}
//關(guān)閉廣告,隱藏浮層
$("#closeAd").click(function(){
$("#wapDocCookie").hide();
$.cookie("docCookie","adDocCookie",{expires:60});
});});
//jQuery cookie library
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
}
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;
}
};
2.第二種:自己寫一個(gè)js操作cookie的實(shí)例
相關(guān)js如下:
$(document).ready(function() {function writeCookie(name,value)
{
var exp = new Date();
exp.setTime(exp.getTime() + 7*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//讀取cookies
function readCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg)){
return unescape(arr[2]);
}else {
return null;
}
}
var adCookie = readCookie("adCookie");if(adCookie!="adDocCookie"){
$("#wapDocCookie").show();
}
//如果本地存在詞條cookie,不顯示浮層
if(adCookie=="adDocCookie"){
$("#wapDocCookie").hide();
}//關(guān)閉廣告,隱藏浮層
$("#closeAd").click(function(){
$("#wapDocCookie").hide();
});
});
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com