发布一个JavaScript工具类库jutil(1)(3)
Cookie & localStorage相关
jutil.getCookie(sKey)
jutil.setCookie(sKey, sValue, iExpireSeconds)
jutil.deleteCookie(sKey)
jutil.getStorage(sKey)//如果浏览器支持HTML5本地存储(localStorage)优先用本地存储,否则用cookie,下同
jutil.setStorage(sKey, sValue, iExpireSeconds)
jutil.deleteStorage(sKey)
实现代码如下:
- getCookie: function (sKey) {
- if (!sKey)
- return "";
- if (document.cookie.length > 0) {
- var startIndex = document.cookie.indexOf(sKey + "=")
- if (startIndex != -1) {
- startIndex = startIndex + sKey.length + 1
- var endIndex = document.cookie.indexOf(";", startIndex)
- if (endIndex == -1) {
- endIndex = document.cookie.length;
- }
- return decodeURIComponent(document.cookie.substring(startIndex, endIndex));
- }
- }
- return ""
- },
- setCookie: function (sKey, sValue, iExpireSeconds) {
- if (!sKey)
- return;
- var expireDate = new Date();
- expireDate.setTime(expireDate.getTime() + iExpireSeconds * 1000);
- this.document.cookie = sKey + "=" + encodeURIComponent(sValue) +
- ";expires=" + expireDate.toGMTString() + ";";
- },
- deleteCookie: function (sKey) {
- if (!sKey)
- return;
- this.document.cookie = sKey + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
- },
- getStorage: function (sKey) {
- if (!sKey)
- return;
- if (window.localStorage) {
- return decodeURIComponent(localStorage.getItem(sKey));
- }
- else {
- return this.getCookie(sKey);
- }
- },
- setStorage: function (sKey, sValue, iExpireSeconds) {
- if (!sKey)
- return;
- if (window.localStorage) {
- localStorage.setItem(sKey, encodeURIComponent(sValue));
- }
- else {
- this.setCookie(sKey, sValue, iExpireSeconds);
- }
- },
- deleteStorage: function (sKey) {
- if (!sKey)
- return;
- if (window.localStorage) {
- localStorage.removeItem(sKey);
- }
- else {
- this.deleteCookie(sKey);
- }
- },
<< 上一页 1 2 34 5 下一页>>
- 上一篇:JavaScript,只有你想不到
- 下一篇:JavaScript宝座:七大框架论剑