addCookie("age","21"); //后三个参数为可选项 function addCookie(key,value,day,path,domin) { //1.解决保留的门路 //找到html文件前的 / 索引 var index = window.location.pathname.lastIndexOf("/"); var currentIndex = window.location.pathname.slice(0,index); path = path || currentIndex; //2.解决默认保留的domin(域名) domin = domin || document.domin; //3.解决输出的工夫 if (!day){ document.cookie = key + "=" + value + ";path=" + path + ";domin=" + domin; }else { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = key + "=" + value + ";expires=" + date.toGMTString() + ";path=" + path + ";domin=" + domin; } }