2

我有一个简单的 jQuery 脚本,允许用户将产品添加到购物篮并查看动画。 http://jsfiddle.net/Z6ave/7/

现在,我有一个小问题,似乎无法找到一个合理的解决方案。

正如您在代码中看到的,当您将产品添加到购物篮时,会分配 order 属性:

Product that was added 1st - Order 1
Product that was added 2nd - Order 2
Product that was added 3rd - Order 3
Product that was added 4th - Order 4
Product that was added 5th - Order 5
Product that was added 6th - Order 6

依此类推……没关系,每个位置都附有特定的 CSS 规则。

但是,如果我删除了中间的一些产品或任何其他不是最后一个的产品,然后当我添加另一个产品时,我需要它来填补空白。

现在发生的事情是……如果我从上面的列表中删除产品编号 3,然后再添加一个,列表将如下所示:

Product that was added 1st - Order 1
Product that was added 2nd - Order 2
Product that was added 4th - Order 4
Product that was added 5th - Order 5
Product that was added 6th - Order 6
Product that was added 7th - Order 7

你看问题出在数字 3 的空白处,所以 7 实际上应该在 3 以下。

你能帮我解决这个问题吗?我知道必须有一些简单/优雅的解决方案。

谢谢

4

1 回答 1

1

我之前添加了一条评论。这是通过数组执行此操作的示例:http: //jsfiddle.net/Z6ave/8/

我创建了一个数组var removedArray = [];

然后当您删除它添加到数组中的项目时:

$(".del").live("click", function() {
var removed = $(this).parent().attr("order");
removedArray.push(removed);
$(this).parent().remove(); });

并在创建元素时使用它

if(removedArray.length > 0){

  var deletedNumber = removedArray[0];

  inbasketimage.addClass("slot" + deletedNumber);
  inbasketimage.attr("order", deletedNumber);
  inbasketimage.find("img").attr("src", img.attr("src"));
  inbasketimage.attr("product_name", productName);

  removedArray.shift();

}else{

  if(isNaN(order)) {
    order = 1;
  } else {
    order = order + 1;
  }

  inbasketimage.addClass("slot" + order);
  inbasketimage.attr("order", order);
  inbasketimage.find("img").attr("src", img.attr("src"));
  inbasketimage.attr("product_name", productName);
}
于 2013-05-31T12:25:03.400 回答