Skip to content

Commit ad1242e

Browse files
committed
Day15
1 parent fde797e commit ad1242e

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

15 - LocalStorage/index-START.html

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,55 @@ <h2>LOCAL TAPAS</h2>
2626
</div>
2727

2828
<script>
29+
const itemInput = document.querySelector('[name="item"]');
2930
const addItems = document.querySelector('.add-items');
3031
const itemsList = document.querySelector('.plates');
3132
const items = [];
33+
const storage = localStorage;
34+
restoreOptions();
35+
36+
function restoreOptions() {
37+
const storageItems = (storage.items) ? JSON.parse(storage.items) : [];
38+
items.push(...storageItems);
39+
renderList();
40+
}
41+
42+
function renderList() {
43+
itemsList.innerHTML = items.map((item, i) => {
44+
const checked = (item.done) ? "checked" : "";
45+
return `
46+
<li>
47+
<input type="checkbox" data-index="${i}" id="item${i}" ${checked}>
48+
<label for="item${i}">${item.text}</label>
49+
</li>
50+
`;
51+
}).join("");
52+
}
53+
54+
function addItemHandler(e) {
55+
e.preventDefault();
56+
const itemText = itemInput.value;
57+
items.push({
58+
text: itemText,
59+
done: false
60+
});
61+
storage.setItem('items', JSON.stringify(items));
62+
renderList();
63+
itemInput.value = "";
64+
}
65+
66+
function changeStateHandler(e) {
67+
if (e.target.tagName.toLowerCase() === 'input') {
68+
const theItemIndex = e.target.dataset.index;
69+
console.log(theItemIndex);
70+
const state = !items[theItemIndex].done;
71+
items[theItemIndex].done = state;
72+
storage.setItem('items', JSON.stringify(items));
73+
}
74+
}
75+
76+
addItems.addEventListener('submit', addItemHandler);
77+
itemsList.addEventListener('click', changeStateHandler);
3278

3379
</script>
3480

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,14 @@
2222
- Day9 + 10 -- 2017/01/05
2323
- `console.time(name)` + `console.timeEnd(name)`
2424
- `console.group(name)` + `console.groupEnd(name)`
25-
- Holding down the `Shift`key could be captured by `MouseEvents` and `KeyboardEvents` with `event.shiftKey` (true for holding down shift key)
25+
- Holding down the `Shift`key could be captured by `MouseEvents` and `KeyboardEvents` with `event.shiftKey` (true for "is holding down shift key")
2626
- Day11 + 12 -- 2017/01/06
2727
- Day13 -- PASS (欸)
2828
- Day14 -- 2017/01/20
2929
- 這章好重要,前陣子也有認真看了一下JS裡面`by value`跟`by reference`的問題,另外開一個區塊寫XD
30+
- Day15 -- 2017/01/28 (新年寫code...廠廠)
31+
- `JSON.parse(null)`是OK的,但`JSON.parse(undefined)`就會跳error。
32+
3033

3134
## Notes
3235
### Day14 - JavaScript References VS Copying

0 commit comments

Comments
 (0)