ajax更新一个类元素

时间:2013-05-14 00:33:13

标签: php jquery

我有一个购物车,上面有购物车列表中的商品清单。当一个被删除时,它会通过ajax更新购物车,但是每个购物车项目的数组中的项目编号将不会更新,除非页面被刷新。

<input class="remove_cart_id" type="hidden" value="'.$i.'" />

$ i表示数组中的数字。如果删除了一个项目,这可能会影响数组的顺序,所以我想为每个类更新$ i。

除了必须输出整个购物车内容之外,还有一种简单的方法来更新每个类的元素。对于购物车数组中的每个项目,可以很容易地使用$ i = 0和i ++。

更新:

$('.remove_cart_item').click(function(){
$(this).parent().stop(true, true).fadeOut();
var pid = $('.remove_cart_id', this).val();
$.ajax({        
    type    : 'POST',
    url     : 'ajax/remove-cart.php',
    data    : 'pid='+pid,
    success : function(data) {
        $('#cart_quantity').html(data);
    }
});
// update cart array
var i = 0; 
$('.remove_cart_id').each(function(){ 
    $(this).val(i); 
    i++; 
};

});

我现在正在使用此代码,但由于代码停止工作,每个函数似乎都存在某种错误。

2 个答案:

答案 0 :(得分:0)

要根据班级更改值,请尝试

$(".classname").each(function() {
   $(this).val('change');
});

类通常适用于组合在一起的多个元素。如果在同一个类中有另一个元素,则也会对其应用值更改。

答案 1 :(得分:0)

假设您需要重新索引值

function reindexCart(){
  var count = 0;
  $('.remove_cart_id').each(){
    $(this).val(count);
    count++;
  }
}

或者,你需要递减值吗?