반응형
LocalStorage
Code
<script>
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = JSON.parse(localStorage.getItem('items')) || [];
const addItem = (e) => {
e.preventDefault();
const text = (e.target.querySelector('[name=item]')).value;
const item = {
text,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
e.target.reset();
}
const 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('');
}
const toggleDone = (e) => {
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, itemsList);
}
addItems.addEventListener('submit', addItem);
itemsList.addEventListener('click', toggleDone);
populateList(items, itemsList);
</script>
느낀 점 & 배운 점
localstorage를 이용해 todolist를 만드는 느낌의 과제였습니다.
그외에 특별한건 없었습니다.
반응형
'공부 정리 > jsChallenge' 카테고리의 다른 글
js challenge day 17 (0) | 2023.02.14 |
---|---|
js challenge day 16 (0) | 2023.02.13 |
js challenge day 14 (0) | 2023.02.10 |
js Challenge day 13 (0) | 2023.02.08 |
js challenge day 12 (0) | 2023.02.07 |
댓글