開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Safari(Web browser)
Head First HTML5 Programming (Elisabeth Robson (著)、Eric Freeman (著)、O'Reilly Media)の Chapter 9.(Storing Things Locally: Web Storage)、EXERCISE(No. 6639) を取り組んでみる。
EXERCISE(No. 6639)
コード(Emacs)
HTML5
<pre id="output0"></pre> <input id="note_text" type="text"> <button id="add_button">Add Sticky Note to Self</button> <br> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample2.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), btn2 = document.querySelector('#add_button'), input0 = document.querySelector('#note_text'), pre0 = document.querySelector('#output0'), p = (x) => pre0.textContent += x + '\n'; let createSticky = () => { let value = input0.value, key = `sticky_${localStorage.length}`; localStorage.setItem(key, value); let stickiesArray = localStorage['stickiesArray']; if (stickiesArray) { stickiesArray = JSON.parse(stickiesArray); } else { stickiesArray = []; localStorage.setItem('stickiesArray', JSON.stringify(stickiesArray)); } stickiesArray.push(key); localStorage.setItem('stickiesArray', JSON.stringify(stickiesArray)); }; btn2.onclick = createSticky; let init = () => { let stickiesArray = localStorage['stickiesArray']; if (stickiesArray) { stickiesArray = JSON.parse(stickiesArray); } else { stickiesArray = []; localStorage.setItem('stickiesArray', JSON.stringify(stickiesArray)); } stickiesArray.forEach((key) => { let value = localStorage[key]; p(value); }); }; let output = () => { init(); }; btn0.onclick = output; btn1.onclick = () => pre0.textContent = ''; output();
0 コメント:
コメントを投稿