我一直在修改以下代码以删除单击“快速添加到购物车”按钮时的弹出窗口。我已成功删除弹出窗口,但现在面临新问题。除非我手动刷新页面,否则购物车项目不会自动更新(不显示)。我已将单击事件侦听器附加到购物车图标以更新购物车项目,但这对我不起作用。
// Function to update the cart items inside the cart drawer
function updateCartItems(cart) {
const cartItemsContainer = document.getElementById('cart-items-container');
// Clear the current cart items
while (cartItemsContainer.firstChild) {
cartItemsContainer.removeChild(cartItemsContainer.firstChild);
}
// Add the updated cart items
cart.items.forEach(item => {
const cartItemElement = document.createElement('div');
cartItemElement.textContent = item.title + ' - ' + item.quantity; // Customize how you want to display the items
cartItemsContainer.appendChild(cartItemElement);
});
}
function onQuickBuyButtonClicked(id, pro_id) {
const CartCount = document.getElementsByClassName('Header__CartCount')[0];
$(".loader_" + id).addClass("add-success--adding");
const product = {
id: id,
quantity: 1
};
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: JSON.stringify(product),
dataType: 'json',
headers: {
'Content-Type': 'application/json'
},
success: function(cart) {
setTimeout(function() {
$(".loader_" + id).removeClass("add-success--adding");
$(".loader_" + id).addClass("add-success--added");
// cartRecommended(pro_id);
// Update the cart items inside the cart drawer immediately
updateCartItems(cart);
}, 500);
setTimeout(function() {
document.dispatchEvent(new CustomEvent('cart:refresh', {
bubbles: true,
detail: {
variant: cart
}
}));
}, 1200);
setTimeout(function() {
$(".loader_" + id).removeClass("add-success--adding").removeClass("add-success--added");
}, 1600);
setTimeout(function() {
// $('#backdrop').addClass('backdrop_active');
}, 2000);
},
error: function(errorThrown) {
$(".loader_" + id).removeClass("add-success--adding");
var r = jQuery.parseJSON(errorThrown.responseText);
$(".error_" + pro_id).html("Error: " + r.description).show();
setTimeout(function() {
$(".error_" + pro_id).html("").hide(100);
}, 3000);
}
});
return false;
}
// Listen for the 'cart:refresh' event and update the cart count
document.addEventListener('cart:refresh', function() {
$.getJSON('/cart.js', function(cart) {
const cartCount = cart.item_count || 0;
const CartCount = document.getElementsByClassName('Header__CartCount')[0];
if (CartCount) {
CartCount.innerHTML = cartCount;
}
});
});
// Attach click event listener to the cart icon to update cart items when clicked
const cartIcon = document.querySelector('.cart-icon');
if (cartIcon) {
cartIcon.addEventListener('click', function() {
// Fetch the cart data and update the cart items when the cart icon is clicked
$.getJSON('/cart.js', function(cart) {
updateCartItems(cart); // Update the cart items inside the cart drawer
});
});
}