答案 0 :(得分:0)
表格就在那里,因为我需要测试一些东西......你可以删除那部分。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form>
Items: <input type="text" id="items"><br>
Date: <input type="text" id="date"><br>
Price: <input type="text" id="price"><br>
<input type="submit" value="Submit" onClick="saveItem()" >
</form>
<table id="tbl-items" class="table table-bordered"><thead><tr><th>Items</th><th>Date</th><th>Price</th></tr></thead><tbody id="tbl-items-body"></tbody></table>
<script>
document.getElementById('form-signin').addEventListener('submit', saveItem);
function saveItem(){
var bill=[];
var expense= { // didn't need the variables.
items: document.getElementById('items').value,
date: document.getElementById('date').value,
price: document.getElementById('price').value
}
if(localStorage.getItem('bill') != null){
bill = JSON.parse(localStorage.getItem('bill'));
}
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill))
console.log(bill);
}
function fetchResult(){
var bill = JSON.parse(localStorage.getItem('bill'));
var totalItems = 0;
var totalPrice = 0;
for(var i=0;i < bill.length;i++){
totalItems++;
totalPrice += bill[i].price;
$("#tbl-items-body").append(
$('<tr>').append(
'<td>' + bill[i].items + '</td><td>' + bill[i].date + '</td><td>' + bill[i].price + '</td>'
)
);
}
$("#tbl-items-body").append(
$('<tr>').append(
'<td>Total Items: ' + totalItems + '</td><td>Total Price: ' + totalPrice + '</td>'
)
);
}
</script>
答案 1 :(得分:0)
在添加价格值并在表格中显示时,在fetchResult
功能中,将价格添加到总变量中,然后显示。
function fetchResult(){
...
result.innerHTML='';
var total = 0;
for(var i=0;i < bill.length;i++){
var items= bill[i].items;
var date= bill[i].date;
var price= bill[i].price;
total += price;
result.innerHTML+= '<table class="table table-bordered">' + '<tr>'+
'<th>'+'Items'+'</th>'+
....
<span> total </span>
}