1
document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);
}
e.preventDefault();
}
沒有錯誤,如果無法添加到已初始化數組
if(localStorage.getItem('bill')==null)
,但在其他的
Uncaught TypeError: Cannot read property 'push' of undefined
at HTMLFormElement.saveItem
當本地存儲是空的,但數據存儲總會有誤差如果不是,則不能添加數據。