javascript 本地和会话存储
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 本地和会话存储相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous">
<title>Task List</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col s12">
<div id="main" class="card">
<div class="card-content">
<span class="card-title">Task List</span>
<div class="row">
<form id="task-form" action="index.php">
<div class="input-field col s12">
<input type="text" name="task" id="task" value="">
<label for="task">New Task</label>
</div>
</div>
<button id="add" class="btn">Add</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<script src="app.js"></script>
</body>
</html>
// set local storage item
// localStorage.setItem('name', 'John');
// localStorage.setItem('age', '30');
// set session storage item
// sessionStorage.setItem('name', 'Beth');
// remove from storage
// localStorage.removeItem('name');
// get from storage
// const name = localStorage.getItem('name');
// const age = localStorage.getItem('age');
// // clear local storage
// localStorage.clear();
// console.log(name, age);
document.querySelector('form').addEventListener('submit', function(e){
const task = document.getElementById('task').value;
let tasks;
if(localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
alert('Task saved');
e.preventDefault();
});
const tasks = JSON.parse(localStorage.getItem('tasks'));
tasks.forEach(function(task){
console.log(task);
});
以上是关于javascript 本地和会话存储的主要内容,如果未能解决你的问题,请参考以下文章
我啥时候应该使用 PHP 会话、浏览器本地存储和 JavaScript 对象参数?
javascript 本地存储会话存储JSON.parse
javascript 模拟本地存储会话存储业力,Jasmine
在PHP和JavaScript中设置Cookie会话存储(SessionStorage)和本地存储(LocalStorage)
javascript 本地/会话存储 - 获取/设置对象包装器
如何使用 javascript 而不是 Django 会话将表单数据(Django 表单)存储到浏览器的本地存储?