Я использую JavaScript для моего веб-сайта электронной коммерции ювелирных изделий для функциональной проверки, но я застрял на том, где я ошибся, так как в своем коде, так как я новичок в компьютерном программировании. У меня есть проблема с объявлением Const $ Cartelement, но я не прочитал. < /P>
Вот мой код JavaScript < /p>
$(document).ready(function() {
// cache jquery selector
const $menuCartElement = $('.menu-cart');
const $cartsItemsElement = $('.cart-list');
const $cartElement = $('.cart');
const $productElement = $('.product');
// initialize cart items count
let cart = [];
//m function to add product to the cart
function addToCart(productElement) {
const $productElement = $(productElement);
const productId = $productElement.data('product');
const productName = $productElement.data('product-title').text();
const productPrice = parseFloat($productElement.data('product-price').text().replace('$', ''));
const productImage = $productElement.find('.product-img img').attr('src');
let existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
const newItem = {
id: productId,
name: productName,
price: productPrice,
image: productImage,
quantity: 1
};
// Add new item to cart
cart.push(newItem);
}
// Update cart count
updateCartCount();
// re-render cart items
renderCartItems();
}
// function to update cart count
function updateCartCount() {
const itemcount = cart.reduce((total, item) => total + item.quantity, 0);
$menuCartElement.find('.cart-count').text(itemcount);
}
// function to render cart items
function renderCartItems() {
//clear existing items
$cartsItemsElement.empty();
if (cart.length === 0) {
//display image of empty cart
$cartsItemsElement.html (`
Your Cart is Empty
`);
} else {
// iterate through cart items and display them
$.each(cart, function(index, item){
const $cartItemElement = $(` total + item.price * item.quantity, 0);
const tax = subtotal * 0.15; // Assuming 15% tax
const total = subtotal + tax;
$('#total-price .cart-amout-value').text(`$${subtotal.toFixed(2)}`);
$('#tax .cart-amount-value').text(`$${tax.toFixed(2)}`);
$(`#final-price .cart-amount-value`).text(`$${total.toFixed(2)}`);
}
// event handler
// event listener for adding product to the cart
$productElement('.product-cart-btn').on('click', function(){
const productElement = $(this).closest('.product');
addToCart(productElement);
})
});
< /code>
Это мой код CSS < /p>
Your Cart
Subtotal
$0.00
Tax included (15%)
$0.00
Total
$0.00
Checkout
Подробнее здесь: https://stackoverflow.com/questions/796 ... g-properly
Оформление на корзину JavaScript не работает должным образом ⇐ Javascript
Форум по Javascript
-
Anonymous
1751652750
Anonymous
Я использую JavaScript для моего веб-сайта электронной коммерции ювелирных изделий для функциональной проверки, но я застрял на том, где я ошибся, так как в своем коде, так как я новичок в компьютерном программировании. У меня есть проблема с объявлением Const $ Cartelement, но я не прочитал. < /P>
Вот мой код JavaScript < /p>
$(document).ready(function() {
// cache jquery selector
const $menuCartElement = $('.menu-cart');
const $cartsItemsElement = $('.cart-list');
const $cartElement = $('.cart');
const $productElement = $('.product');
// initialize cart items count
let cart = [];
//m function to add product to the cart
function addToCart(productElement) {
const $productElement = $(productElement);
const productId = $productElement.data('product');
const productName = $productElement.data('product-title').text();
const productPrice = parseFloat($productElement.data('product-price').text().replace('$', ''));
const productImage = $productElement.find('.product-img img').attr('src');
let existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
const newItem = {
id: productId,
name: productName,
price: productPrice,
image: productImage,
quantity: 1
};
// Add new item to cart
cart.push(newItem);
}
// Update cart count
updateCartCount();
// re-render cart items
renderCartItems();
}
// function to update cart count
function updateCartCount() {
const itemcount = cart.reduce((total, item) => total + item.quantity, 0);
$menuCartElement.find('.cart-count').text(itemcount);
}
// function to render cart items
function renderCartItems() {
//clear existing items
$cartsItemsElement.empty();
if (cart.length === 0) {
//display image of empty cart
$cartsItemsElement.html (`
[i]
Your Cart is Empty
`);
} else {
// iterate through cart items and display them
$.each(cart, function(index, item){
const $cartItemElement = $(` total + item.price * item.quantity, 0);
const tax = subtotal * 0.15; // Assuming 15% tax
const total = subtotal + tax;
$('#total-price .cart-amout-value').text(`$${subtotal.toFixed(2)}`);
$('#tax .cart-amount-value').text(`$${tax.toFixed(2)}`);
$(`#final-price .cart-amount-value`).text(`$${total.toFixed(2)}`);
}
// event handler
// event listener for adding product to the cart
$productElement('.product-cart-btn').on('click', function(){
const productElement = $(this).closest('.product');
addToCart(productElement);
})
});
< /code>
Это мой код CSS < /p>
Your Cart
Subtotal
$0.00
Tax included (15%)
$0.00
Total
$0.00
Checkout
Подробнее здесь: [url]https://stackoverflow.com/questions/79690563/javascript-cart-checkout-isnt-working-properly[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия