Home >Web Front-end >JS Tutorial >js encapsulates the function code of cookie operation_javascript skills

js encapsulates the function code of cookie operation_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:32:21837browse

Core code:

Copy code The code is as follows:

var cookie={
setCookie:function (name, value, iDay) {
var oDate = new Date();
oDate.setDate(oDate.getDate() iDay);
document.cookie = name '=' value ';expires=' oDate;
},
getCookie:function (name) {
var arr = document.cookie.split('; ');
for (var i = arr.length - 1; i >= 0; i--) {
var arr2 = arr[i].split('=');
if(arr2[0]===name){
return arr2[1];
}
}
return '';
},
removeCookie:function (name) {
cookie.setCookie(name,1,-1) ;
}
};

Test:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> var cookie={ setCookie:function (name, value, iDay) { var oDate = new Date(); oDate.setDate(oDate.getDate()+iDay); document.cookie = name+'='+value+';expires='+oDate; }, getCookie:function (name) { var arr = document.cookie.split('; '); for (var i = arr.length - 1; i >= 0; i--) { var arr2 = arr[i].split('='); if(arr2[0]===name){ return arr2[1]; } } return ''; }, removeCookie:function (name) { cookie.setCookie(name,1,-1); } }; cookie.setCookie('username','iceshu',33); // setCookie('pwd','ff',365); cookie.removeCookie('username'); alert(document.cookie) alert(cookie.getCookie('pwd')); </script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn