在電商平臺的開發(fā)中,購物車功能是一個核心模塊,而其中復選框的聯(lián)動操作(如選中父級分類時,其下的所有子級商品也被選中)則是提升用戶體驗的關鍵。本文將詳細解析如何使用原生JavaScript實現(xiàn)復選框的父子級聯(lián)動,并逐步構建一個簡易的購物車數(shù)據(jù)處理服務。
一、理解復選框聯(lián)動邏輯
復選框聯(lián)動的核心邏輯在于事件監(jiān)聽與DOM操作。當用戶點擊父級復選框時,我們需要找到其對應的所有子級復選框,并將它們的選中狀態(tài)與父級同步。反之,當所有子級復選框都被選中時,父級復選框也應自動變?yōu)檫x中狀態(tài);若部分子級被選中,則父級應顯示為不確定狀態(tài)。
二、HTML結構設計
構建一個清晰的HTML結構,模擬購物車中的商品分類與商品項:`html
電子產(chǎn)品
`
三、JavaScript實現(xiàn)聯(lián)動功能
1. 父級控制子級
為父級復選框添加點擊事件,當選中時,將其所有子級復選框設為選中;取消選中時,則將子級全部取消。`javascript
const parentCheckboxes = document.querySelectorAll('.parent-checkbox');
parentCheckboxes.forEach(parent => {
parent.addEventListener('change', function() {
const category = this.getAttribute('data-category');
const childCheckboxes = document.querySelectorAll(.child-checkbox[data-category="${category}"]);
childCheckboxes.forEach(child => {
child.checked = this.checked;
});
});
});`
2. 子級影響父級狀態(tài)
為每個子級復選框添加事件監(jiān)聽,當子級狀態(tài)變化時,檢查其所屬父級下的所有子級選中情況,更新父級狀態(tài)。`javascript
const childCheckboxes = document.querySelectorAll('.child-checkbox');
childCheckboxes.forEach(child => {
child.addEventListener('change', function() {
const category = this.getAttribute('data-category');
const parentCheckbox = document.querySelector(.parent-checkbox[data-category="${category}"]);
const siblings = document.querySelectorAll(.child-checkbox[data-category="${category}"]);
const checkedCount = Array.from(siblings).filter(cb => cb.checked).length;
if (checkedCount === 0) {
parentCheckbox.checked = false;
parentCheckbox.indeterminate = false;
} else if (checkedCount === siblings.length) {
parentCheckbox.checked = true;
parentCheckbox.indeterminate = false;
} else {
parentCheckbox.checked = false;
parentCheckbox.indeterminate = true;
}
});
});`
四、構建購物車數(shù)據(jù)處理服務
聯(lián)動功能完成后,我們需要一個服務來處理選中的商品數(shù)據(jù),例如計算總價、生成訂單列表等。
#### 1. 數(shù)據(jù)收集函數(shù)
創(chuàng)建一個函數(shù),遍歷所有被選中的子級復選框,提取商品信息(如名稱、價格等)。`javascript
function getSelectedItems() {
const selectedItems = [];
document.querySelectorAll('.child-checkbox:checked').forEach(checkbox => {
selectedItems.push({
name: checkbox.value,
category: checkbox.getAttribute('data-category'),
// 可從其他屬性或數(shù)據(jù)集中獲取價格等
});
});
return selectedItems;
}`
2. 計算總價
假設每個商品項都有一個關聯(lián)的價格數(shù)據(jù)(可通過data-price屬性存儲),我們可以計算選中商品的總價。`javascript
function calculateTotalPrice() {
let total = 0;
document.querySelectorAll('.child-checkbox:checked').forEach(checkbox => {
const price = parseFloat(checkbox.getAttribute('data-price')) || 0;
total += price;
});
return total;
}`
3. 更新購物車顯示
將數(shù)據(jù)服務與UI結合,實時顯示選中商品列表和總價。`javascript
function updateCartDisplay() {
const items = getSelectedItems();
const total = calculateTotalPrice();
// 更新DOM元素,例如顯示總價的span
document.getElementById('total-price').textContent = 總價: ¥${total.toFixed(2)};
// 可選:更新商品列表
console.log('已選商品:', items);
}
// 在每次復選框狀態(tài)變化后調用更新
const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
allCheckboxes.forEach(cb => {
cb.addEventListener('change', updateCartDisplay);
});`
五、優(yōu)化與擴展
- 性能優(yōu)化:對于大量商品,可使用事件委托減少事件監(jiān)聽器數(shù)量。
- 狀態(tài)持久化:結合
localStorage保存選中狀態(tài),避免頁面刷新后數(shù)據(jù)丟失。 - 與后端交互:將選中的商品數(shù)據(jù)通過AJAX發(fā)送到服務器,實現(xiàn)完整的購物車業(yè)務流程。
###
通過上述步驟,我們實現(xiàn)了一個具備復選框聯(lián)動功能的購物車前端模塊,并構建了簡單的數(shù)據(jù)處理服務。這不僅是前端交互的基礎,也是理解數(shù)據(jù)驅動視圖的實踐案例。你可以在此基礎上,根據(jù)實際需求擴展更多功能,如商品數(shù)量增減、優(yōu)惠券計算等,打造更完善的購物體驗。