index.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> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="main.js"></script> </head> <body> <h1 class="bg-primary text-white p-2">Memo page</h1> <div class="container"> <p class="h5">type message:</p> <div class="alert alert-primary"> <input type="text" class="form-control" id="message"> <button class="btn btn-primary mt-2" id="btn"> Save</button> </div> <table class="table" id="table"></table> <div class="text-center"> <button class="btn btn-danger mt-4" id="initial"> Initialize </button> </div> </div> </body> </html>
index.ts
let table:HTMLTableElement let message:HTMLInputElement function showTable(html:string){ table.innerHTML = html } function doAction(){ const msg = message.value memo.add({message:msg, date:new Date()}) memo.save() memo.load() showTable(memo.getHtml()) } function doInitial(){ memo.data = [] memo.save() memo.load() message.value = '' showTable(memo.getHtml()) } type Memo = { message:string, date:Date } class MemoData { data:Memo[] = [] add(mm:Memo):void { this.data.unshift(mm) } save():void { localStorage.setItem('memo_data', JSON.stringify(this.data)) } load():void{ const readed = JSON.parse(localStorage.getItem('memo_data')) this.data = readed ? readed : [] } getHtml():string { let html = '<thead><th>memo</th><th>data</th></thead><tbody>' for(let item of this.data){ html += '<tr><td>' + item.message + '</td><td>' + item.date.toLocaleString() + '</td></tr>' } return html + '</tbody>' } } const memo = new MemoData() window.addEventListener('load', ()=> { table = document.querySelector('#table') message = document.querySelector('#message') document.querySelector('#btn').addEventListener('click', doAction) document.querySelector('#inital').addEventListener('click', doInitial) memo.load() showTable(memo.getHtml()) })
これなんだよな やりたいこと