我有一个简单的购物车系统,当用户浏览网站时,我使用JQuery来更新购物车项目。
我遇到的问题是,在用户将某些产品重新添加到购物系统后,删除功能不起作用。只有在页面刷新后它才会再次开始工作,然后在用户添加更多产品后停止...
故事是这样的:
以下是处理删除的代码:
/**
* Delete an item from the cart
*/
$('.del-goods').click(function(){
var itemId = $(this).data("item");
var url = "/cart/delete/item_id/" + itemId;
$('#item-delete-' + itemId).html('<div style="color:red;">Deleting...</div>');
//Set up Ajax to update the customers cart
$.ajax({
type: 'POST',
async: true,
url: url,
dataType: "json",
success: function(responseObject){
//If the response is successful
if (responseObject.success)
{
$('.cart-info-count').text(responseObject.cart_item_count);
$('.cart-info-value').text(responseObject.cart_item_total);
$('#item-' + itemId).remove();
} else {
alert("Failed to delete item!");
}
}
});
});
以下是我的添加到购物车功能。我怀疑当我提取一组新的下拉项目时会出现问题,其中包括删除链接......
$('.add2cart').click(function() {
//The click event relating to the add product area
var productId = $(this).data("product");
var area = $(this).data("area");
//Get the product quantity
var quantity = $('#' + area).find('input[name="productQuantity"]').val();
//Make sure the quantity is an integer and not a float
if ( Math.floor(quantity) != quantity)
{
quantity = 1;
}
//Make sure the quantity is numeric and not characters
if ( ! $.isNumeric(quantity) )
{
quantity = 1;
}
//If quantity is zero, make it 1
if ( quantity == 0 )
{
quantity = 1;
}
//Controller Route
var url = '/cart/update-quantities/prod_id/' + productId + '/quantity/' + quantity;
//Change the icon text to processing...
$('#' + area).find('.add2cart').text('Processing...');
//Update the datbase with the new cart item
$.ajax({
type: 'POST',
async: true,
url: url,
dataType: "json",
success: function(responseObject){
//If the response is successful
if (responseObject.success)
{
//Write success to the clicked button
$('#' + area).find('.add2cart').text('SUCCESS...');
//Reset button to original state
window.setTimeout(function () {
$('#' + area).find('.add2cart').text('ADD TO CART');
}, 1500);
//Update the view with the correct items in the cart
$('.cart-info-count').text(responseObject.cart_item_count);
//Update the view with the new cart total
$('.cart-info-value').text(responseObject.cart_item_total);
//Update the HTML (this pulls a whole fresh set of HTML)
$('#cart-dropdown').html(responseObject.cart_item_dropdown_html);
} else {
//Write failed to the clicked button
$('#' + area).find('.add2cart').text('FAILED...');
//Reset button to original state
window.setTimeout(function () {
$('#' + area).find('.add2cart').text('ADD TO CART');
}, 1500);
}
}
});
});
答案 0 :(得分:1)
您必须使用事件委派,因为内容会动态更改。
$(document).on('click','.del-goods',function(){