效果图:
实现思路:
body部分:
<div class="wrapper">
<h2>Local Tapas</h2>
<ul class="plates">
<li>Loading Tapas...</li>
</ul>
<form class="add-items">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+AddItem">
</form>
</div>
js部分:
- 所要用到的变量
- 添加按钮:
const addItems = document.querySelector('.add-items');
- todoList列表
const itemList = document.querySelector('.plates');
- 本地缓存,将所有的todoItem进行缓存。
const items = JSON.parse(localStorage.getItem('items'))||[];
- 添加item事件
1. 监听addItems的submit事件,当用户点击提交按钮或者点击enter键时触发;
2. localStorage的常用API:
localStorage.setItem('key',value);
设置以key-value
形式本地缓存
localStorage.getItem('key');
根据key值获取本地缓存对应的值。
localStorage.clear();
清空本地的缓存
localStorage.removeItem('key');
删除key所对应的缓存。
3. localStorage中只能存储字符串,所以必须用JSON.stringify(obj)
将一个对象转换为字符串,再使用JSON.parse(objString)
将字符串转换为对象。
4.this.reset();将表单重置。
function addItem(e) {
e.preventDefault();//阻止默认事件的触发,防止在提交时页面自己刷新
const text = (this.querySelector('[name=item]')).value;
const item = {
text,//text:text;
done: false //确定是否完成图标
};
items.push(item);
populateList(items, itemList);//将其item展示出来。
localStorage.setItem('items', JSON.stringify(items));
//添加完数据之后,重置输入框
this.reset();
}
addItems.addEventListener('submit', addItem);
- 列表显示:
将所有列表项转化为li传入页面的html中。
代码:
//设置默认值,防止传参出错的时候crash
//之所以用‘’空字符是因为如果用null的话,会出现在html中
function populateList(plates = [], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
`;
}).join('');//join()之后一定要加‘’,表示空字符,否则会加入逗号,造成错误
}
- 状态的转换:
使用了事件委托。对input列表的父组件进行事件监听,让他们的父元素处于监听状态,当我们所点击的元素是其子元素,就告诉它的子元素,执行相应的事件。
通过
e.target.matches('input')
判断所点击的元素是不是input元素,e.target返回所点击的宿主元素。
代码:
//切换完成状态
function toggleDone(e) {
//跳过所有的input,只处理label
if (!e.target.matches('input')) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemList);
}
itemList.addEventListener('click', toggleDone);
- 清除缓存
//清除LocalStorage缓存,尤其在生产环境中
window.onbeforeunload=function (e) {
localStorage.removeItem('items');
e.returnValue=confirmationMessage;
}
总结:
在页面加载的时候,先获取本地缓存的items,若存在就传给变量items,若第一次登录或者无item,初始化为空数组;
在页面加载的时候先加载页面的所有todoList,再执行populateList(items, itemsList);