購物車核心功能:商品列表展示、數量增減(含上下限)、單品小計、總價計算、刪除商品、與後端 API 同步狀態。本文基於 jQuery + EasyUI 實現完整流程。
// 單一商品物件結構
{
id: "P001", // 商品ID
productname: "筆記型電腦",
price: 25000, // 單價
num: 2 // 數量
}
$('.add').on('click', function() { // 建議用 on() 替代已棄用的 live()
var $li = $(this).closest('li');
var $ul = $(this).closest('ul');
var num = parseInt($li.find('#num').text()) || 0;
var productId = $li.find('#productId').val();
var price = parseFloat($ul.find('#price').text()) || 0;
var totalPrice = parseFloat($('#totalprice').text()) || 0;
if (num >= 99) { alert('單品數量上限 99'); return; }
num++;
var itemTotal = num * price;
var newTotalPrice = totalPrice + price;
// 即時更新 UI
$li.find('#num').text(num);
$ul.find('#total').text(itemTotal.toFixed(2));
// 同步後端
$.post('<%=basePath%>updateShopCart.action',
{ productId: productId, num: num },
function(data) {
if (data.success) {
$('#totalprice').text(newTotalPrice.toFixed(2));
} else {
// 失敗回滾 UI
num--;
$li.find('#num').text(num);
$ul.find('#total').text((num * price).toFixed(2));
alert('更新失敗:' + data.msg);
}
}, 'json'
);
});
$('.delete').on('click', function() { // 類名建議改為 .reduce
var $li = $(this).closest('li');
var $ul = $(this).closest('ul');
var num = parseInt($li.find('#num').text()) || 1;
var productId = $li.find('#productId').val();
var price = parseFloat($ul.find('#price').text()) || 0;
var totalPrice = parseFloat($('#totalprice').text()) || 0;
if (num <= 1) { alert('數量不可小於 1'); return; }
num--;
var itemTotal = num * price;
var newTotalPrice = totalPrice - price;
$li.find('#num').text(num);
$ul.find('#total').text(itemTotal.toFixed(2));
$.post('<%=basePath%>updateShopCart.action',
{ productId: productId, num: num },
function(data) {
if (!data.success) {
num++; // 回滾
$li.find('#num').text(num);
$ul.find('#total').text((num * price).toFixed(2));
alert('更新失敗:' + data.msg);
} else {
$('#totalprice').text(newTotalPrice.toFixed(2));
}
}, 'json'
);
});
$('#cha').on('click', function() {
if (!confirm('確定移除此商品?')) return;
var $ul = $(this).closest('ul');
var productId = $ul.find('#productId').val();
$.post('<%=basePath%>deleteFromShopCart.action',
{ productId: productId },
function(data) {
if (data.success) {
loadCart(); // 重新載入整個購物車
} else {
alert('刪除失敗:' + data.msg);
}
}, 'json'
);
});
function loadCart() {
$.ajax({
type: 'POST',
url: '<%=basePath%>findShopCart.action',
dataType: 'json',
success: function(data) {
var list = data.list || [];
$('#main_t_l').empty();
var grandTotal = 0;
if (list.length === 0) {
$('#main_t_l').html('<p class="empty-cart">購物車是空的</p>');
$('#totalprice').text('0.00');
return;
}
list.forEach(function(item) {
var itemTotal = item.price * item.num;
grandTotal += itemTotal;
var row = '<ul class="cart-item">'
+ '<li style="width:17%">' + item.productname + '</li>'
+ '<li style="width:17%" id="price">' + item.price + '¥</li>'
+ '<li style="width:30%">'
+ '<input type="hidden" id="productId" value="' + item.id + '">'
+ '<button class="num-btn">' + item.num + '</button>'
+ '<button class="reduce">-</button>'
+ '<button class="add">+</button>'
+ '</li>'
+ '<li style="width:16%" id="total">' + itemTotal.toFixed(2) + '</li>'
+ '<li style="width:10%"><button class="remove" id="cha">×</button></li>'
+ '</ul>';
$(row).appendTo('#main_t_l');
});
$('#totalprice').text(grandTotal.toFixed(2));
}
});
}
| 問題 | 改進方案 |
|---|---|
重複 ID (#num, #price) |
改用 class + data-* 屬性 |
.live() 已棄用 |
改用 .on() 事件委派 |
| 浮點數精度問題 | 金額以「分」為單位存整數,或用 toFixed(2) + Math.round |
| UI 與資料強耦合 | 採用 MVVM (Vue/React) 或至少分離渲染函式 |
| 無 Loading 狀態 | 請求期間禁用按鈕、顯示 Spinner |
// Vue 3 Composition API 範例
import { ref, computed } from 'vue';
const cartItems = ref([]);
const loading = ref(false);
const totalPrice = computed(() =>
cartItems.value.reduce((sum, item) => sum + item.price * item.num, 0)
);
async function updateQuantity(itemId, delta) {
const item = cartItems.value.find(i => i.id === itemId);
if (!item) return;
const newNum = item.num + delta;
if (newNum < 1 || newNum > 99) return;
loading.value = true;
try {
const res = await api.updateCart(itemId, newNum);
if (res.success) item.num = newNum;
} finally {
loading.value = false;
}
}