有没有办法用javascript重置/清除浏览器的localStorage?


当前回答

localStorage.clear();

or

window.localStorage.clear();

清除特定项目

window.localStorage.removeItem("item_name");

要按id删除特定值,请执行以下操作:

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

其他回答

使用此选项清除localStorage:

localStorage.clear();
window.localStorage.clear(); //try this to clear all local storage

这里有一个函数,允许您删除所有localStorage项,但有例外。这个函数需要jQuery。你可以下载要点。

你可以这样称呼它

let clearStorageExcept = function(exceptions) {
  let keys = [];
  exceptions = [].concat(exceptions); // prevent undefined

  // get storage keys
  $.each(localStorage, (key) => {
    keys.push(key);
  });

  // loop through keys
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    let deleteItem = true;

    // check if key excluded
    for (let j = 0; j < exceptions.length; j++) {
      let exception = exceptions[j];
      if (key == exception) {
        deleteItem = false;
      }
    }

    // delete key
    if (deleteItem) {
      localStorage.removeItem(key);
    }
  }
};
localStorage.clear();

or

window.localStorage.clear();

清除特定项目

window.localStorage.removeItem("item_name");

要按id删除特定值,请执行以下操作:

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

手动按钮:

<script>
function ask() {
if (confirm('Clear localStorage?') == true) {
localStorage.clear()
location.reload()
}
else {
alert('Nothing happend')
}
}
}
</script>
<style>
button {border-width:0px;background-color:#efefef;padding:5px;width:5cm;margin:5px;}
</style>
<button onclick=ask()>Clear localStorage</button>