如何用JQuery移除购物车商品?解决函数未定义报错
解决购物车移除函数未定义报错问题
问题描述
报错信息:Uncaught ReferenceError: removeItemFromCart is not defined onclick
使用jQuery实现购物车商品移除功能,其他函数正常运行,已尝试调试和清除缓存,问题仍存在。
问题代码
$(document).ready(function() { $(".add-to-cart-btn").click(function(e) { e.preventDefault(); var productId = $(this).data("id"); console.log("Product ID:", productId); var productName = $(this).data("product-name"); var productImage = $(this).data("product-image"); var quantity = parseInt($("#quantity-input").val()); //store the product ID in the session. var productImage = "img/" + productId + ".jpg"; var productPrice = parseFloat($("#product-price-" + productId).text().replace("R", "")); var totalPrice = productPrice * quantity; //store the product details in the session. var cartItems = JSON.parse(sessionStorage.getItem("cartItems")) || []; cartItems.push({ productId: productId, quantity: quantity, productImage: productImage, productName: productName }); sessionStorage.setItem("cartItems", JSON.stringify(cartItems)); $.ajax({ type: "POST", url: "add-to-cart.php", data: { productId: productId }, success: function(response) { alert(response); updateCartBadge(); // Update the cart badge with the new count getCartItem(); // Refresh the cart items after adding }, error: function(xhr, status, error) { alert("An error occurred while adding the item to the cart."); console.log(xhr.responseText); } }); }); // Function to update cart badge. function updateCartBadge(userId) { $.ajax({ type: "GET", url: "getCartItemCount.php", data: { userId: userId}, success: function (response) { console.log('Cart Item Count:', response); $("#cart-badge").text(response); // Update the cart badge count }, error: function (xhr, status, error) { alert("An error occurred while retrieving the cart item count."); console.log(xhr.responseText); } }); } // Function to update cart items in the modal function updateCartItems(cartData) { var cartItems = cartData.cartItems; var cartContainer = $("#cart-items"); // Clear the previous content cartContainer.empty(); // Loop through the cart items and add them to the HTML cartItems.forEach(function (item) { var totalPrice = item.totalPrice || 0; // Ensure totalPrice is a valid number or set it to 0 var cartItemHtml = ` <tr> <td>${item.product_name}</td> <td><img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail"></td> <td>R${totalPrice.toFixed(2)}</td> <td>${item.quantity}</td> <td><button class="btn btn-danger btn-sm" data-productId="${item.product_id}" onclick="removeItemFromCart(${item.product_id})">Remove </button></td> </tr> `; // Append the cart item HTML to the container cartContainer.append(cartItemHtml); }); // Update the total price var totalPriceContainer = $("#total-price"); totalPriceContainer.text("Total Price: R" + cartData.totalPrice.toFixed(2)); } // Use event delegation to handle click events for // "Remove" buttons inside the modal $("#cartModal").on("click", ".remove-cart-item", function () { var productId = $(this).data("productId"); removeItemFromCart(productId); }); //removing item from cart. function removeItemFromCart(productId) { $.ajax({ type: "POST", url: "removeCartItem.php", data: { productId: productId }, // Include the product ID in the data dataType: "json", success: function (response) { if (response.success) { // Item removed successfully, update the cart display getCartItemsForModal(); updateCartItems(); } else { alert(response.message); // Display the error message from the server } }, error: function (xhr, status, error) { alert("An error occurred while removing the item from the cart."); console.log(xhr.responseText); }, }); } // Call the backend to fetch cart data when the cart modal is opened $("#cartModal").on("show.bs.modal", function () { $.ajax({ type: "GET", url: "getCartData.php", dataType: "json", success: function (cartData) { console.log("Response from the server:", cartData); updateCartItems(cartData); updateCartBadge(); }, error: function (xhr, status, error) { alert("An error occurred while fetching cart item details"); console.log(xhr.responseText); } }); }); // function to populate the cart modal with cart items. function getCartItemsForModal() { $.ajax({ type: "GET", url: "getCartItem.php", dataType: "html", success: function (response) { $("#cart-items").html(response); }, error: function (xhr, status, error) { console.log("An error occured while retrieving cart items"); console.log(xhr.responseText); }, }); } updateCartItems(); //call getCartItemsForModal function. $("#cart-badge-btn").click(function () { getCartItemsForModal(); }); // function to get item from the cart. function getCartItem() { $.ajax({ type: "GET", url: "getCartItem.php", success: function(response) { $("#cart-items").html(response); // Update the cart items on the page }, error: function(xhr, status, error) { alert("An error occurred while retrieving the cart items."); console.log(xhr.responseText); } }); } // Call updateCartBadge and getCartItem on page load updateCartBadge(); getCartItem(); });
问题原因
- 作用域问题:
removeItemFromCart函数定义在$(document).ready()的回调内部,属于局部作用域,无法被全局的内联onclick事件访问。 - 事件逻辑冲突:代码同时使用了内联
onclick和jQuery事件委托,两种方式的作用域不兼容。
解决方案
方案1:移除内联事件,统一使用jQuery事件委托(推荐)
步骤1:修改购物项HTML模板
在updateCartItems函数中,移除按钮的onclick属性,添加remove-cart-item类(和已有的事件委托选择器匹配):
function updateCartItems(cartData) { var cartItems = cartData.cartItems; var cartContainer = $("#cart-items"); cartContainer.empty(); cartItems.forEach(function (item) { var totalPrice = item.totalPrice || 0; // 移除onclick,添加remove-cart-item类 var cartItemHtml = ` <tr> <td>${item.product_name}</td> <td><img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail"></td> <td>R${totalPrice.toFixed(2)}</td> <td>${item.quantity}</td> <td><button class="btn btn-danger btn-sm remove-cart-item" data-productId="${item.product_id}">Remove</button></td> </tr> `; cartContainer.append(cartItemHtml); }); var totalPriceContainer = $("#total-price"); totalPriceContainer.text("Total Price: R" + cartData.totalPrice.toFixed(2)); }
步骤2:确认事件委托逻辑有效
你已有的事件委托代码可以正常工作,确保选择器和类名一致:
$("#cartModal").on("click", ".remove-cart-item", function () { var productId = $(this).data("productId"); removeItemFromCart(productId); });
步骤3:修复移除成功后的更新逻辑
在removeItemFromCart的success回调中,updateCartItems()需要传入数据,直接调用getCartItemsForModal()更简单(它会从后端获取最新HTML并渲染):
function removeItemFromCart(productId) { $.ajax({ type: "POST", url: "removeCartItem.php", data: { productId: productId }, dataType: "json", success: function (response) { if (response.success) { getCartItemsForModal(); updateCartBadge(); // 同步更新购物车徽章数量 } else { alert(response.message); } }, error: function (xhr, status, error) { alert("An error occurred while removing the item from the cart."); console.log(xhr.responseText); }, }); }
方案2:将函数暴露到全局作用域(不推荐)
如果必须保留内联onclick,可以将函数挂载到window对象,让全局能访问:
// 在$(document).ready()内部定义removeItemFromCart后添加: window.removeItemFromCart = removeItemFromCart;
此方法会污染全局作用域,可能引发命名冲突,优先选择方案1。
内容的提问来源于stack exchange,提问作者MyLegend2020 Wilson
相关产品推荐
相关产品推荐

