2010-04-19 30 views
0

我想用ajax建立一個購物網站。當用戶點擊「添加到購物車」圖片。點擊加載圖片將顯示在添加到購物車圖片旁邊。第一次點擊工作正常,圖像顯示如我所料。然而,第二次和下面的點擊會在第一個加載圖像上附加更多圖像(第二個:添加兩個加載圖像,第三個:添加三個圖像...點擊3次後共有6個圖像)。我確實使用了ajaxStop並刪除了第一張圖片......不知道發生了什麼......可以使用幫助。非常感謝。AjaxStart問題

我的JavaScript代碼

// add to cart 
$(".addToCart").click(function(e){ 
$this=$(this); 
$tableId=$this.closest('table').attr('id'); 


$($this).prev().ajaxStart(function(){ 
    $("<img class='loader' src='images/loader.gif'>").insertBefore($this); 
}); 


$($this).prev().ajaxStop(function(){ 
    $($this).prev().remove(); 
}); 

HTML

<table> 
<tr> 
    <td width="146" align="right" valign="middle"> 
<br> 
<span id="wasPrice"><?php echo $productPriceWas; ?></span> 
<br> 

<?php echo "$".$productPrice;?><br>**//I want my image here**<a class="addToCart" href="javascript:void(0);"><img src="images/addToCart.gif" alt="add To Cart"/><a/>  </td> 
     </tr> 
     </table> 
+0

@Jerry - 我從你的意見,我的答案是可以接受的見你可以點擊複選框將其標記爲「接受的答案」。歡迎來到堆棧溢出! – gnarf 2010-04-19 06:09:05

回答

2

.ajaxStart()是一個全球性的事件。每次點擊您都綁定另一組事件處理程序,這會導致顯示2個或更多加載圖像。你可以嘗試使用.one(types, function() { ... })事件綁定,每次點擊只觸發一次該代碼塊。

但是,我會建議看$.ajax()回調beforeSendcomplete作爲綁定代碼的特定ajax請求(而不是每個ajax請求)的地方。

我通常使用的模式是這樣的:

$(".addToCart").click(function(e){ 

    // you need to use "var" to make sure $this is only available inside this function 
    var $this=$(this); 

    // avoid using $ on variables that aren't jQuery objects (this is just a string) 
    var tableId=$this.closest('table').attr('id'); 

    // insert the element before starting the ajax call 
    var $loadingElem = $("<img class='loader' src='images/loader.gif'>"); 
    $loadingElem.insertBefore($this); 

    // call ajax with some data 
    $.ajax({ 
    url: '...', data: {id: tableId}, // .... 
    complete: function(xhr, textStatus) { 
     // remove the element when the ajax completes 
     $loadingElem.remove(); 
    } 
    }); 
}); 

此外,$($this)是一個浪費電話,它只是返回$this

+0

謝謝。我真的從你的答案中學到很多東西。真的很感激它! – FlyingCat 2010-04-19 04:41:43