JS Code block 代码块–Storage (localStorage, sessionStorage)

星期二, 2023-04-18 | Author: Lee | computer, 前端 | 617 views

Storage (localStorage, sessionStorage)
设置localStorage
获取localStorage
移除localStorage
移除所有localStorage
设置sessionStorage
获取sessionStorage
移除sessionStorage
移除所有sessionStorage

/**
 * 设置localStorage
 *
 */
function setLocalStorage(key, val) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
        for(let i in setting){
            window.localStorage.setItem(i, JSON.stringify(setting[i]))
        }
    }else{
        window.localStorage.setItem(key, JSON.stringify(val))
    }
}
/**
 * 获取localStorage
 */
function getLocal(key) {
    if (key) return JSON.parse(window.localStorage.getItem(key))
    return null;
}
 
/**
 * 移除localStorage
 */
function removeLocal(key) {
    window.localStorage.removeItem(key)
}
 
/** 
 * 移除所有localStorage
 */
function clearLocal() {
    window.localStorage.clear()
}
 
/**
 * 设置sessionStorage
 */
function setSession(key, val) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
        for(let i in setting){
            window.sessionStorage.setItem(i, JSON.stringify(setting[i]))
        }
    }else{
        window.sessionStorage.setItem(key, JSON.stringify(val))
    }
}
 
/**
 * 获取sessionStorage
 */
function getSession(key) {
    if (key) return JSON.parse(window.sessionStorage.getItem(key))
    return null;
}
 
/**
 * 移除sessionStorage
 */
function removeSession(key) {
    window.sessionStorage.removeItem(key)
}
 
/**
 * 移除所有sessionStorage
 */
function clearSession() {
    window.sessionStorage.clear()
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2387.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta