2014-01-13 16 views
1

我創建了一個jQuery函數,它在點擊時爲其添加動畫「添加到購物車」按鈕,以便它飛到頂欄上的購物車圖標。我克隆了div標籤,因爲我仍然希望添加到購物車按鈕在用戶點擊一次之後可用,然後設置了animate函數以刪除完成後向上飛行的div。jQuery元素在動畫後未被移除

我的問題是,一旦函數運行一次,它不會再運行。例如,如果客戶點擊添加到購物車按鈕,然後決定再次點擊該按鈕,則該按鈕將不會第二次被動畫化。

這是我的JavaScript代碼 - 它可能看起來有點過於複雜,但這是由於按鈕在我正在處理的頁面上的位置。

$('.addToCart').click(function(){ 

    var leftPos = $(this).position().left + $(this).parent().offset().left; 
    var existingLeftCSS = $(this).css('margin-left'); 
    var existingTopCSS = $(this).css('margin-top'); 
    var leftPos = parseFloat(leftPos) - parseFloat(existingLeftCSS); 
    var topPos = $(this).offset().top - $(window).scrollTop()+'px'; 
    var topPos = parseFloat(topPos) - parseFloat(existingTopCSS); 
    var newLeftPos = $('#cartButton').offset().left - parseInt($(this).css('margin-left')); 

    setTimeout(function(){$(this).remove();}, 110); 
    $(this).clone().appendTo($(this).parent()); 
    $(this).css('z-index','999'); 


    $(this) 
    .css({ 
     position:'fixed', 
     top: topPos, 
     left: leftPos 
    }) 
    .animate({ 
    top:"40", 
    left: newLeftPos 

    }, 500, function(){ 
    $(this).remove(); 
    }); 


}); 

或我的問題的簡化版本,看到這樣的jsfiddle: http://jsfiddle.net/jxbbm/

回答

1

替換$(this).clone()... for

var clone = $(this).clone(); 
    $(clone).appendTo($(this).parent()); 
    $(clone).css('z-index','999'); 
    $(clone).css({ 
       position:'fixed', 
       top: topPos, 
       left: leftPos }) 
    .animate({ 
      top:"8", 
      left: newLeftPos 
    }, 500, function(){ 
       $(this).remove(); 
    }); 
+0

正是我所需要的!謝謝 –

+0

您的歡迎:) – Sebastien

2

我認爲你應該使用的事件delegetion,像這樣:

$('.productBox').on('click', '.addToCart', function() { 
    ... 
}); 
1

變化的第一行的代碼到

$('.productBox').on('click', '.addToCart', function(){