<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>todoList待办事项</title><script src="./js/jquery.min.js"></script>
</head><body><header><section><label for="title">ToDoList</label><input type="text" id="title" placeholder="添加ToDo"></section></header><section><h2>正在进行<span id="rodocount"></span></h2><ol id="todolist" class="demo-box"></ol><h2>已经完成<span id="rodocount"></span></h2><ul id="donelist"></ul></section><footer>Copyright ©2014 todolist.cn</footer><script>var todolist = [{title: '我今天吃了八个馒头',done: false}, {title: '我今天学习jq',done: false}, ];localStorage.setItem("todo", JSON.stringify(todolist));//本地的数组转换为json.stringfy();var data = localStorage.getItem("todo");console.log(typeof data);//获取本地存储数据需要把字符串数据转换为对象形式json.parsedata = JSON.parse(data);console.log(data);$(function() {//todolist渲染到界面load();//按下回车 把完整数据存储到本地存储里面$("#title").on("keydown", function(event) {if (event.keyCode === 13) {//先读取本地存储原来的数据var local = getDate();console.log(local);//把local数组更新元素local.push({title: $(this).val(),done: false});//把这个数组给本地存储saveDate(local);}})//读取本地存储的数据function getDate() {var data = localStorage.getItem("todolist");if (data !== null) {//本地存储里面的数据是字符串格式的return JSON.parse(data);} else {//返回一个数组return [];}}//保存数据function saveDate(data) {localStorage.setItem("todolist", JSON.stringify(data));}//渲染数据function load() {//读取本地的数据var data = getDate(data);console.log(data);//遍历之前清空$("ol").empty();//遍历整个数据$.each(data, function(i, n) {console.log(n);$("ol").prepend("<li><input type='checkbox'><p>" + n.title + "</p><a href='javascript:;'></a></li>");})}});</script>
</body></html>
运行结果