** 代码由 3 个独立的 HTML 文件组成,如下所示: **
1-“SHOP.html”表示商店的 HTML 文件(我们可以从中选择产品)
2-“SPRODUCT.html”具有不同内容的 HTML 文件,表示单个选定产品的模板(包括“添加到购物车”按钮,用于将选定产品添加到购物车)
3-“CART.html”代表购物车的 HTML 文件(我想在其中包含“SPRODUCT.html”中所选产品的列表)。
每当我从 SHOP 中选择产品时,产品详细信息会在 SPRODUCT 模板中占据一席之地,然后,我按“添加到购物车”按钮将其添加到购物车。然后,我回到商店选择其他产品。
问题是: 1- 当我按下“添加到购物车”按钮(代表当时的特定产品)时,我丢失了数据集“cartData”中先前选择的产品的旧保存数据。
这是我的 HTML 文件及其 Javascript 代码:
文件:SPRODUCT.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blessed Sweets</title>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.15.4/css/all.css" />
<link rel="stylesheet" href="style.css">
<script src="sproduct.js" async></script>
</head>
<!--################################# HEADER & COVER ######################## -->
<body>
<section id="header">
<a href="#"><img src="img/logo_lined0.png" class="logo" alt="" width="550" height="140" onclick="hrefFunctionHome()"></a>
<div>
<ul id="navbar">
<li><a herf="index.html" onclick="hrefFunctionHome()">Home</a></li>
<li><a class="active" herf="shop.html" onclick="hrefFunctionShop()">Shop</a></li>
<li><a herf="blog.html" onclick="hrefFunctionBlog()">Blog</a></li>
<li><a herf="about.html" onclick="hrefFunctionAbout()">About</a></li>
<li><a herf="contact.html" onclick="hrefFunctionContact()">Contact</a></li>
<li><a herf="cart.html" onclick="hrefFunctionCart()"><i class='fas fa-shopping-cart' style='font-size:30px;color:rgba(142, 19, 113, 0.878)'></i></a></li>
</div>
<script>
function hrefFunctionHome() {
window.location.href='index.html';
}
function hrefFunctionShop(){
window.location.href='shop.html';
}
function hrefFunctionBlog() {
window.location.href='blog.html';
}
function hrefFunctionAbout() {
window.location.href='about.html';
}
function hrefFunctionContact() {
window.location.href='contact.html';
}
function hrefFunctionCart() {
window.location.href='cart.html';
}
</script>
<script>
function hrefFunctionShop() {
window.location.href='shop.html';
}
</script>
</section>
<section id="prodetails" class="section-p1">
<div class="single-pro-img">
<a class="single-pro-img-class"></a>
</div>
<div class="single-pro-details">
<span class="prod-brand"></span>
<h5 class="prod-name"></h5>
<div class="star">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<h5 class="prod-price"></h5>
<select>
<option>SELECT TYPE OF NUTS (Stuffing and Decoration)</option>
<option>الكاوكاو</option>
<option>اللوز</option>
<option>الجوز</option>
<option>الفستق</option>ذ
<option>خليط من كل المكسرات</option>
</select>
<input type="number" value="1">
<a class="add-cart-button"><button class="normal">Add To Cart</button></a>
</div>
</section>
<section id="newsletter" class="section-p1">
<div class="newstext">
<h4>Sign Up For News Letters</h4>
<p>Get our updates for our latest products and offers</p>
</div>
<div class="form">
<input type="text" placeholder="Your Email address">
<button class="normal">Sign Up</button>
</div>
</section>
<footer class="section-p1">
<div class="col">
<img class="logo" src="img/logo_lined0.png" alt="" width="250" height="70">
<h4>CONTACT</h4>
<p><strong>Address:</strong> 112, 112, El-Alia est, Biskra, Algeria</p>
<p><strong>Phone:</strong> +213 556 10 66 16</p>
<p><strong>Working Hours:</strong> 9:00 to 18:00 - Saturday To Thursday</p>
<div class="follow">
<h4>FOLLOW US</h4>
<div class="icon">
<i class="fab fa-facebook-f" style='font-size:30px'></i>
<i class="fab fa-instagram" style='font-size:30px'></i>
<i class="fab fa-tiktok"style='font-size:30px'></i>
</div>
</div>
</div>
<div class="col">
<h4>ABOUT</h4>
<a href="#">About Us</a>
<a href="#">Delivery Information</a>
<a href="#">Privacy Policy</a>
<a href="#">Terms and Conditions</a>
<a href="#">Contact Us</a>
</div>
<div class="col">
<h4>MY ACCOUNT</h4>
<a href="#">Sign In</a>
<a href="#">Help</a>
</div>
<div class="payment">
<h4>PAYMENT METHOD</h4>
<p>Secured Payment Getway With The Golden CARD</p>
<img src="img/payment0.png" alt="" width="200" height="110">
<span>البطاقة الذهبية</span>
</div>
<div class="copyright">
<p>@ 2023, Blessed Sweets of Biskra</p>
</div>
</footer>
<!-- <script>
var MainImg = document.getElementById("MainImg");
var smallimg = document.getElementsByClassName("small-img");
smallimg[0]. onclick = function(){
MainImg.src = smallimg[0].src;
}
smallimg[1]. onclick = function(){
MainImg.src = smallimg[1].src;
}
smallimg[2]. onclick = function(){
MainImg.src = smallimg[2].src;
}
</script> -->
<script>
</script>
</body>
</html>
文件:SPRODUCT.js
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() { // ############# READY TO START ##################################
// ############# SPRODUCT PAGE AND CALCULATIONS ########################################
var addToCartButtons = document.getElementsByClassName('add-cart-button')
console.log(addToCartButtons)
let sproductData = JSON.parse(localStorage.getItem("sproductData"));
console.log(sproductData)
var sproductImgItems = document.getElementsByClassName("single-pro-img-class")[0] // 1st Get the class where to add a line
let sproducImgtHTML = `
<img src="${sproductData[3]}" width="100%" class="prod-img" id="MainImg" alt="">` // 2nd write the line to be added including the vatiable
sproductImgItems.innerHTML = sproducImgtHTML; // 3rd Apply the line to the HTML code
var sproductBrandItems = document.getElementsByClassName("prod-brand")[0]
let sproductBrandHTML = `
Brand: ${sproductData[0]}`
sproductBrandItems.innerHTML = sproductBrandHTML;
var sproductNameItems = document.getElementsByClassName("prod-name")[0] // 1st Get the class where to add a line
let sproducNametHTML = `
Name: ${sproductData[1]}` // 2nd write the line to be added including the vatiable
sproductNameItems.innerHTML = sproducNametHTML; // 3rd Apply the line to the HTML code
var sproductPriceItems = document.getElementsByClassName("prod-price")[0] // 1st Get the class where to add a line
let sproducPricetHTML = `
Price: ${sproductData[2]}` // 2nd write the line to be added including the vatiable
sproductPriceItems.innerHTML = sproducPricetHTML; // 3rd Apply the line to the HTML code
// ########## ADD TO CART BUTTON ########################################################
var addToCartButtons = document.getElementsByClassName('add-cart-button')
console.log(addToCartButtons)
const cartItem = [];
var button = addToCartButtons[0]
button.addEventListener('click', function (event){
var button = event.target
var shopItem = button.parentElement.parentElement.parentElement
var title = shopItem.getElementsByClassName('prod-name')[0].innerText.replace('Name:','')
var price = shopItem.getElementsByClassName('prod-price')[0].innerText.replace('Price:', '').replace('DZD', '')
var imgSrc = shopItem.getElementsByClassName('prod-img')[0].src
console.log(title, price, imgSrc)
// return(title, price, imgSrc)
const productItem = [title, price, imgSrc]
cartItem.push(productItem);
localStorage.setItem('cartData', JSON.stringify(cartItem));
console.log(cartItem)
});
}
// function addToCartClicked(event){
// var button = event.target
// var shopItem = button.parentElement.parentElement.parentElement
// var title = shopItem.getElementsByClassName('prod-name')[0].innerText.replace('Name:','')
// var price = shopItem.getElementsByClassName('prod-price')[0].innerText.replace('Price:', '').replace('DZD', '')
// var imgSrc = shopItem.getElementsByClassName('prod-img')[0].src
// console.log(title, price, imgSrc)
// // return(title, price, imgSrc)
// const productItem = [title, price, imgSrc]
// cartItem.push(productItem);
// // console.log(cartData)
// localStorage.setItem('cartData', JSON.stringify(cartItem));
// }
// const addButton = document.getElementById('add-to-cart');
// const cartItems = [];
// addButton.addEventListener('click', function() {
// // Get the product details
// const productName = prompt('Enter the product name:');
// const productPrice = prompt('Enter the product price:');
// // Add the product to the cart
// const product = { name: productName, price: productPrice };
// cartItems.push(product);
// // Save the cart to localStorage
// localStorage.setItem('cart', JSON.stringify(cartItems));
// });
// // Check if the cart data exists in localStorage
// if (!localStorage.getItem('cartData')) {
// // If the cart data does not exist, initialize it as an empty array
// localStorage.setItem('cartData', JSON.stringify([]));
// const array1=[title, price, imgSrc]
// localStorage.setItem('cartData', JSON.stringify(cartData[0]));
// }else{
// const array2=[title, price, imgSrc]
// localStorage.setItem('cartData', JSON.stringify(cartData[1]));
// }
文件:CART.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blessed Sweets</title>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.15.4/css/all.css" />
<link rel="stylesheet" href="style.css">
<script src="cart.js" async></script>
</head>
<!--################################# HEADER & COVER ######################## -->
<body>
<section id="header">
<a href="#"><img src="img/logo_lined0.png" class="logo" alt="" width="550" height="140" onclick="hrefFunctionHome()"></a>
<div>
<ul id="navbar">
<li><a herf="index.html" onclick="hrefFunctionHome()">Home</a></li>
<li><a herf="shop.html" onclick="hrefFunctionShop()">Shop</a></li>
<li><a herf="blog.html" onclick="hrefFunctionBlog()">Blog</a></li>
<li><a herf="about.html" onclick="hrefFunctionAbout()">About</a></li>
<li><a herf="contact.html" onclick="hrefFunctionContact()">Contact</a></li>
<li id="lag-bag"><a class="active" herf="cart.html" onclick="hrefFunctionCart()"><i class='fas fa-shopping-cart' style='font-size:30px;color:rgba(142, 19, 113, 0.878)'></i></a></li>
</div>
<script>
function hrefFunctionHome() {
window.location.href='index.html';
}
function hrefFunctionShop(){
window.location.href='shop.html';
}
function hrefFunctionBlog() {
window.location.href='blog.html';
}
function hrefFunctionAbout() {
window.location.href='about.html';
}
function hrefFunctionContact() {
window.location.href='contact.html';
}
function hrefFunctionCart() {
window.location.href='cart.html';
}
</script>
</section>
<section id="page-header" class="cart-header">
<h2>#CheckTheBill</h2>
<h3>!تحقق من فاتورتك</h3>
</section>
<section id="cart" class="section-p1">
<table width="100%">
<thead>
<tr>
<td>REMOVE</td>
<td>IMAGE</td>
<td>PRODUCT</td>
<td>PRICE</td>
<td>QUANTITY</td>
<td>SUBTOTAL</td>
</tr>
<tbody class="cart-items">
</tbody>
</thead>
</table>
</section>
<section id="cart-add" class="section-p1">
<div id="coupon">
<h3>Apply Coupon</h3>
<div>
<input type="text" placeholder="Enter your coupon">
<button class="normal">Apply</button>
</div>
</div>
<div id="subtotal">
<h3>Cart Totals</h3>
<table>
<tr>
<td>Cart Subtotal</td>
<td class="cart-total-price"></td>
</tr>
<tr>
<td>Shipping</td>
<td>Free</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td class="cart-total-price"></td>
</tr>
</table>
<button class="normal">Proceed to checkout</button>
</div>
</section>
<!--################################# FOOTER ######################## -->
<footer class="section-p1">
<div class="col">
<img class="logo" src="img/logo_lined0.png" alt="" width="250" height="70">
<h4>CONTACT</h4>
<p><strong>Address:</strong> 112, 112, El-Alia est, Biskra, Algeria</p>
<p><strong>Phone:</strong> +213 556 10 66 16</p>
<p><strong>Working Hours:</strong> 9:00 to 18:00 - Saturday To Thursday</p>
<div class="follow">
<h4>FOLLOW US</h4>
<div class="icon">
<i class="fab fa-facebook-f" style='font-size:30px'></i>
<i class="fab fa-instagram" style='font-size:30px'></i>
<i class="fab fa-tiktok"style='font-size:30px'></i>
</div>
</div>
</div>
<div class="col">
<h4>ABOUT</h4>
<a href="#">About Us</a>
<a href="#">Delivery Information</a>
<a href="#">Privacy Policy</a>
<a href="#">Terms and Conditions</a>
<a href="#">Contact Us</a>
</div>
<div class="col">
<h4>MY ACCOUNT</h4>
<a href="#">Sign In</a>
<a href="#">Help</a>
</div>
<div class="payment">
<h4>PAYMENT METHOD</h4>
<p>Secured Payment Getway With The Golden CARD</p>
<img src="img/payment0.png" alt="" width="200" height="110">
<span>البطاقة الذهبية</span>
</div>
<div class="copyright">
<p>@ 2023, Blessed Sweets of Biskra</p>
</div>
</footer>
<script>
let cartData = JSON.parse(localStorage.getItem("cartData"));
var cartItems = document.getElementsByClassName("cart-items")[0]
for (var i = 0; i<cartData.length; i++) {
this["cartData"+i]=cartData[i]
}
let cartHTML1 = `
<tr class="cart-row">
<td><a href="#" type="button" class="cart-remove-button"><i class="far fa-times-circle"></i></a></td>
<td><img src="${cartData0[2]}" alt=""></td>
<td>${cartData0[0]}</td>
<td class="cart-price">DZD ${cartData0[1]}</td>
<td><input class="cart-quantity-input" type="number" value="1"></td>
<td class="cart-sub-total">DZD ${cartData0[1]}</td>
</tr>`;
cartItems.innerHTML = cartHTML1;
let cartHTML2 = `
<tr class="cart-row">
<td><a href="#" type="button" class="cart-remove-button"><i class="far fa-times-circle"></i></a></td>
<td><img src="${cartData1[2]}" alt=""></td>
<td>${cartData1[0]}</td>
<td class="cart-price">DZD ${cartData1[1]}</td>
<td><input class="cart-quantity-input" type="number" value="1"></td>
<td class="cart-sub-total">DZD ${cartData1[1]}</td>
</tr>`;
cartItems.innerHTML = cartHTML1 + cartHTML2;
</script>
</body>
</html>
文件:CART.js
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() { // ############# READY TO START ###############
// ############# CART PAGE AND CALCULATIONS ###############
var removeCartItemButtons= document.getElementsByClassName('cart-remove-button')
console.log(removeCartItemButtons)
for (var i = 0 ; i<removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs= document.getElementsByClassName('cart-quantity-input')
for (var i = 0 ; i<quantityInputs.length; i++) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
console.log(cartData)
// // Check if the cart data exists in localStorage
// if (!localStorage.getItem('cartData')) {
// // If the cart data does not exist, initialize it as an empty array
// localStorage.setItem('cartData', JSON.stringify([]));
// }
updateCartTotal()
updateSubTotal()
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.parentElement.remove()
updateCartTotal()
}
function quantityChanged(event){
var input = event.target
if (isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
updateSubTotal()
}
function updateSubTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
// console.log(quantityElement)
var price = parseFloat(priceElement.innerText.replace('DZD', ''))
console.log(price)
var quantity = quantityElement.value
subtotal = (price * quantity)
console.log(subtotal)
document.getElementsByClassName('cart-sub-total')[i].innerText = 'DZD ' + subtotal
}
// total = Math.round(total * 100) / 100
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('DZD', ''))
console.log(price)
var quantity = quantityElement.value
total = total + (price * quantity)
console.log(total)
}
// total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = 'DZD ' + total
document.getElementsByClassName('cart-total-price')[1].innerText = 'DZD ' + total
}
// for (var i = 0 ; i<removeCartItemButtons.length; i++) {
// var button = removeCartItemButtons[i]
// function removeCartRow() {
// console.log('clicked')
// var buttonClicked = event.target
// buttonClicked.parentElement.parentElement.parentElement.remove()
// }
// }
1- 我希望在按下 SPRODUCT.html 模板中常见的“添加到购物车”按钮后保存和维护所有选定的产品。但它确实实现了这一点。
2- 我不知道如何创建一个在“cartData”中循环并显示 cartData 中的所有产品的“for”循环,而不仅仅是第一个。我认为这需要在“for”循环中创建 cartHTML 变量,但我不知道如何实现。
您能否为我提供指导,以完成我认为可以解决的上述两项任务?