---
# System prepended metadata

title: localStorage - 瀏覽器資料儲存
tags: [JavaScript]

---

###### tags: `JavaScript`

# localStorage - 瀏覽器資料儲存
```javascript=
// 設定
localStorage.setItem(key ,value)
// 取值
localStorage.getItem(key)

// 範例
var str = 'Tom'
var getloc = ''
localStorage.setItem('myName',str)
getloc = localStorage.getItem('myName')
console.log(getloc); // Tom
```

## 基礎範例
```javascript=
<h2>輸入你的姓名</h2>
<input type="text" class="textClass">
<button type="button" class="btn">送出</button>
<button type="button" class="callBtn">呼叫名子</button>

<script>
var textClass = document.querySelector('.textClass')
var btn = document.querySelector('.btn')
var callBtn = document.querySelector('.callBtn')
btn.addEventListener('click', function(){
  // 設定 localStorage 並清空 input
  localStorage.setItem('myName', textClass.value)
  textClass.value = ''
},false)
callBtn.addEventListener('click', function(){
  // input value = localStorage
  textClass.value = localStorage.getItem('myName')
},false)
</script>
```
![](https://i.imgur.com/R2mN0Ml.gif)

## localStorage - 從陣列或物件轉換 String
不論是存入還是取出 localStorage 它一定是 String，所以需要以下兩種語法來解析
- JSON.stringify() - 物件/陣列 轉 字串
- JSON.parse() - 字串 轉 物件/陣列

```javascript=
<script>
var data = [
  {
    name: '小城'
  }
]
var dataString = JSON.stringify(data) // 物件/陣列轉字串
console.log(dataString);
localStorage.setItem('data', dataString)

var getData = localStorage.getItem('data')
var getDataAry = JSON.parse(getData) // 字串轉物件/陣列
console.log(getDataAry);
</script>
```
![](https://i.imgur.com/HwaVP5X.gif)

## data-* - 透過 dataset 讀取自訂資料
data-自訂名稱
```javascript=
<ul>
  <li class="listli" data-num="0" data-dog="3">拉拉</li>
</ul>

<script>
var list = document.querySelector('.listli')
list.addEventListener('click',function(e){
  var num = e.target.dataset.num
  var dog = e.target.dataset.dog
  console.log('num:',num);
  console.log('dog:',dog);
},false)
```
![](https://i.imgur.com/mqpj0tT.gif)

## dataset - array 運用

```javascript=
<style>
  .list{
    padding: 30px;
    background: #868686;
  }
</style>

<ul class="list"></ul>

<script>
var data = [
  {
    name: 'abc'
  },
  {
    name: 'dfg'
  }
]
var list = document.querySelector('.list')
function updateList() {
  var str = '';
  var len = data.length;
  for(var i = 0;len > i;i++){
    str += `<li data-num="${i}">${data[i].name}</li>`
  }
  list.innerHTML = str
};
updateList(); // 渲染 li

list.addEventListener('click', function(e){
  if(e.target.nodeName !== 'LI'){return}
  var num = e.target.dataset.num
  console.log(data[num].name);
})
</script>
```
![](https://i.imgur.com/ke9JGAo.gif)

## splice - 刪除 array 資料
splice(從哪開始, 刪除幾筆資料)
splice(0,1) - 從第 0 筆開始刪除一筆
```javascript=
<style>
  .list{
    padding: 30px;
    background: #868686;
  }
</style>

<ul class="list"></ul>

<script>
var data = [
  {
    name: 'abc'
  },
  {
    name: 'dfg'
  }
]
var list = document.querySelector('.list')
function updateList() {
  var str = '';
  var len = data.length;
  for(var i = 0;len > i;i++){
    str += `<li data-num="${i}">${data[i].name}</li>`
  }
  list.innerHTML = str
};
updateList(); // 渲染 li

list.addEventListener('click', function(e){
  if(e.target.nodeName !== 'LI'){return}
  var num = e.target.dataset.num
  data.splice(num, 1) // 刪除 1 筆
  updateList() // 更新畫面
})
</script>
```

## 小作業 - localStorage 製作 Todos

### 陣列方式

```javascript=
<style>
  .list{
    padding: 15px;
    background: #009688;
    color: #fff;
  }
  li{
    display: flex;
    justify-content: space-between;
    margin-bottom: 1rem;
  }
  li:last-child{
    margin-bottom: 0;
  }
</style>

<input type="text" class="todoText">
<button type="button" class="btn">加入 todo</button>
<ul class="list"></ul>

<script>
var data = JSON.parse(localStorage.getItem('todos')) || [];
var btn = document.querySelector('.btn')
var list = document.querySelector('.list')
var todoText = document.querySelector('.todoText')

btn.addEventListener('click', sendTodo, false)
todoText.addEventListener('keydown', function(e){
  // e.keyCode
  if (e.keyCode === 13) {
    sendTodo()
  }
  // e.key
  // if (e.key === 'Enter') {
  //   sendTodo()
  // }
}, false)
list.addEventListener('click', delTodo, false)
function sendTodo(e) {
  if(!todoText.value.trim()){return}
  data.push(todoText.value)
  localStorage.setItem('todos',JSON.stringify(data))
  todoText.value = ''
  updateList();
}
function updateList() {
  var str = ''
  for (let i = 0; i < data.length; i++) {
    str += `<li><span>${data[i]}</span><button type="button" class="delBtn" data-num="${i}">刪除</button></li>`
  }
  list.innerHTML = str
};
function delTodo(e) {
  if(e.target.nodeName !== 'BUTTON') {return}
  var id = e.target.dataset.num
  data.splice(id, 1)
  localStorage.setItem('todos',JSON.stringify(data))
  updateList();
}
updateList();
</script>
```
![](https://i.imgur.com/BzA8oG1.gif)


### 物件方式
```javascript=
<style>
  .list{
    padding: 15px;
    background: #009688;
    color: #fff;
  }
  li{
    display: flex;
    justify-content: space-between;
    margin-bottom: 1rem;
  }
  li:last-child{
    margin-bottom: 0;
  }
</style>

<input type="text" class="todoText">
<button type="button" class="btn">加入 todo</button>
<ul class="list"></ul>

<script>
var data = JSON.parse(localStorage.getItem('todosObj')) || [];
var btn = document.querySelector('.btn')
var list = document.querySelector('.list')
var todoText = document.querySelector('.todoText')

btn.addEventListener('click', sendTodo, false)
todoText.addEventListener('keydown', function(e){
  // e.keyCode
  if (e.keyCode === 13) {
    sendTodo()
  }
  // e.key
  // if (e.key === 'Enter') {
  //   sendTodo()
  // }
}, false)
list.addEventListener('click', delTodo, false)

function sendTodo(e) {
  if(!todoText.value.trim()){return}
  var todoContent = {
    content: todoText.value
  }
  data.push(todoContent)
  localStorage.setItem('todosObj',JSON.stringify(data))
  todoText.value = ''
  updateList();
}
function updateList() {
  var str = ''
  for (let i = 0; i < data.length; i++) {
    str += `<li><span>${data[i].content}</span><button type="button" class="delBtn" data-num="${i}">刪除</button></li>`
  }
  list.innerHTML = str
};
function delTodo(e) {
  if(e.target.nodeName !== 'BUTTON') {return}
  var id = e.target.dataset.num
  data.splice(id, 1)
  localStorage.setItem('todosObj',JSON.stringify(data))
  updateList();
}
updateList();
</script>
```
![](https://i.imgur.com/2gt0tf5.gif)
