打卡ts day02--使用typescript 写评论demo
demo.ts
// DataHelpler 类 用于操作localStorage class DataHelpler { dataKey: string; //localstorage key primaryKey: string; // id constructor(dataKey: string, primaryKey: string) { this.dataKey = dataKey this.primaryKey = primaryKey } // [{content:'3333', id :1},{content:'3333', id :1}] // 读取本地数据 readData(): any { let pinglunStr: string | null = localStorage.getItem(this.dataKey) let pinglunArr: any = []; // 这一定要给默认值 if (pinglunStr) { pinglunArr = JSON.parse(pinglunStr) } return pinglunArr }
// 存本地数据 saveData(pinglunArr: object[] ): void { let pinglunStr: string = JSON.stringify(pinglunArr) localStorage.setItem(this.dataKey, pinglunStr) }
// 新增本地数据 add(pinglunValue: string): number { // 1.先取值 let Data: any = this.readData() // 2.评论对象 let obj:any = { content: pinglunValue } // 3.自动生成primaryKey obj[this.primaryKey] // 拿到本地存储中最后一个值的primaryKey +1 let newId: number = Data.length > 0 ? Data[Data.length -1][this.primaryKey] + 1 : 1; // 4. 将primaryKey 值 存到obj obj[this.primaryKey] = newId Data.push(obj) this.saveData(Data) return newId }
// 删除 remove(ID: number | string): boolean { debugger // 1.先取值 let Data: any = this.readData() // 2.遍历Data let Index :number = Data.findIndex((item:any) =>item[this.primaryKey] == ID) if(Index !== -1) { Data.splice(Index, 1) this.saveData(Data) return true } return false } }
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> .neirong, .pinglun, .addpinglun { border: 1px solid #000; } </style> <body style="width:50%;margin: 10px auto"> <div class="neirong"> <p>文章内容哈哈哈哈红红火火恍恍惚惚红红火火恍恍惚惚红红火火恍恍惚惚</p> </div> <div class="pinglun"> <ul id="ul"> <!-- <li>评论1112323 <span style="float:right;margin-right:30px;">删除</span> </li> --> </ul> </div> <div class="addpinglun"> <textarea name="" id="textarea" cols="70" rows="10"></textarea> <button id="add">新增评论</button> </div> </body> <script src="./js/demo.js"></script> <script> let dh = new DataHelpler('plData', 'id') window.onload = function () { init() } // 渲染评论列表 function init() { let data = dh.readData() let str = '' if (data) { data.forEach(item => { str += ` <li>${item.content} <span data-id="${item.id}" onclick="del(this)" style="float:right;margin-right:30px;cursor:pointer;">删除</span> </li> ` }); } else { str += ` <li> 暂无数据 </li> ` } document.querySelector('#ul').innerHTML = str } // 新增 document.querySelector('#add').onclick = function () { dh.add(document.querySelector('#textarea').value) init() document.querySelector('#textarea').value = '' } // 删除功能 function del(element) { dh.remove(element.getAttribute("data-id")) init() } </script> </html>
效果图