隨著互聯(lián)網(wǎng)的發(fā)展,網(wǎng)購已經(jīng)成為人們生活的一部分。而網(wǎng)購就離不開一個(gè)重要的組成部分:購物車。在網(wǎng)頁制作中,使用HTML5制作購物車的代碼是一項(xiàng)重要的技能。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>購物車實(shí)現(xiàn)</title> <script type="text/javscript"> //添加商品到購物車 function addToCart() { var itemName = document.getElementById("item-name").innerHTML; var itemPrice = document.getElementById("item-price").innerHTML; var itemNum = document.getElementById("item-num").value; var itemTotalPrice = itemPrice * itemNum; if (localStorage.getItem(itemName) != null) { //如果商品已被添加到購物車,則直接更新數(shù)量和價(jià)格 var oldNum = parseInt(localStorage.getItem(itemName).split(",")[0]); var newNum = oldNum + parseInt(itemNum); var newTotalPrice = itemPrice * newNum; localStorage.setItem(itemName, newNum + "," + newTotalPrice); } else { localStorage.setItem(itemName, itemNum + "," + itemTotalPrice); } showCart(); } //顯示購物車 function showCart() { var cartList = document.getElementById("cart-list"); var cartTotal = document.getElementById("cart-total"); var num = 0; var totalPrice = 0; cartList.innerHTML = ""; for (var i = 0; i< localStorage.length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); var data = value.split(","); if (data.length == 2) { //如果數(shù)據(jù)格式不正確,則跳過 num += parseInt(data[0]); totalPrice += parseFloat(data[1]); var li = document.createElement("li"); var itemNameSpan = document.createElement("span"); var itemNumSpan = document.createElement("span"); var itemPriceSpan = document.createElement("span"); itemNameSpan.innerHTML = key; itemNumSpan.innerHTML = "x " + data[0]; itemPriceSpan.innerHTML = "¥ " + data[1]; li.appendChild(itemNameSpan); li.appendChild(itemNumSpan); li.appendChild(itemPriceSpan); cartList.appendChild(li); } } cartTotal.innerHTML = "共 " + num + " 件商品,總計(jì)¥ " + totalPrice; } </script> </head> <body> <h1>商品詳情</h1> <div> <span id="item-name">IPhone Xs Max</span> <span id="item-price">8999</span> <input type="number" min="1" max="100" value="1" id="item-num"> <button onclick="addToCart()">加入購物車</button> </div> <h1>購物車詳情</h1> <ul id="cart-list"></ul> <p id="cart-total"></p> </body> </html>
上面的代碼實(shí)現(xiàn)了一個(gè)簡單的購物車功能,當(dāng)用戶點(diǎn)擊“加入購物車”按鈕時(shí),會(huì)將當(dāng)前商品的名稱、單價(jià)、數(shù)量存儲(chǔ)在本地存儲(chǔ)中。同時(shí),還會(huì)通過JavaScript動(dòng)態(tài)地生成購物車列表,以及計(jì)算出購物車的商品總數(shù)量和總價(jià)。