제출하면 체크 박스를 localStorage로 푸시하는 양식이 있습니다.
돌아 오거나 새로 고칠 때 localStorage와 일치하는 값이있는 상자를 확인하고 싶습니다. 내 의견이있는 아래의 Javascript에 조건부가 있습니다. 이것이 적합한 조건입니까?
더 나은 방법이 있다면 공유 해주세요. 저는 실제로 React와 Redux Thunk로 이것을 할 것입니다. 그러나 바닐라 JS로 이것을 시도하고 싶었습니다.
HTML
<form onsubmit='setStorage()'>
<input type='checkbox' value='toy'/> Toy
<input type='checkbox' value='bag'/> Bag
<input type='checkbox' value='cup'/> Cup
<input type='submit' value='Submit'>
</form>
<ul class='cart'>
</ul>
자바 스크립트
const storage = JSON.parse(localStorage.getItem('cart'));
const inputs = document.querySelectorAll('input');
const checkInputs = () => {
inputs.forEach((input) => {
// check if localStorage has matching values with existing input values.
const exist = storage.find((item) => item.name === input.value);
// if exist returns true, then check that input box, otherwise leave box unchecked;
exist ? input.checked === true : input.checked === false;
})
}
const setStorage = () => {
const updatedStorage = [];
inputs.forEach((input) => {
input.checked ? updatedStorage.push({name: input.value}) : null;
})
localStorage.setItem('cart', JSON.stringify(updatedStorage));
}
const setCart = () => {
const cart = document.querySelector('.cart');
storage.forEach((item) => {
const li = document.createElement('li');
const name = document.createElement('p');
name.innerText = item.name;
cart.append(li);
li.append(name);
})
}
checkInputs();
setCart();
이 줄을 변경하면 대신 할당합니다.
exist ? input.checked = true : input.checked = false;
const checkInputs = () => {
inputs.forEach((input) => {
// check if localStorage has matching values with existing input values.
const exist = storage.find((item) => item.name === input.value);
console.log(exist)
// if exist returns true, then check that input box, otherwise leave box unchecked;
exist ? input.checked = true : input.checked = false;
})
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다