2011-05-08 74 views
1

我正在使用以下Ajax函數發送請求。雖然有些奇怪的事情發生。請求完成後,返回的新按鈕不會啓用ajax。它充當了一個正常的錨點。完成ajax請求後,Ajax achor變爲正常的錨!

$(document).ready(function() { 
    $(".UIButton a").click(function(e) { 
     e.preventDefault(); 

     if (! $(this).data("isClicked")) 
     { 
      var requestData = $(this).attr("href"); 
      var link = $(this); 

      $.ajax({ 
       context: this, 
       dataType: 'js', 
       url: requestData, 

       beforeSend: function() { 
        $(link).fadeOut("slow"); 
       }, 

       error: function() { 
       }, 

       success: function(response) { 
        $(link).parent().html(response); 
         $(link).stop().fadeIn("slow"); 
       } 
      }); 

      // Toggle isClicked to prevent button mashing 
      link.data("isClicked", true); 

      // Create timeout to restore button 
      setTimeout(function() { link.removeData("isClicked") }, 1000); 
     } 
    }); 
}); 

下面是來自服務器,這是正確的回: <a class="delete" href="https://stackoverflow.com/users/delete/3333">Delete</a>

原來這裏是按鈕:

<div class="UIButton"> 
    <a class="Add" href="https://stackoverflow.com/users/add/3333">Add</a> 
</div> 

回答

2

因爲當您最初結合事件的鏈接並不存在聽衆click事件,您需要重新綁定事件(在成功函數中使用bind),或使用delegatelive將事件處理程序綁定到事件(推薦nded)。

使用delegatelive可確保現在和將來在匹配元素上處理事件。

這裏是你將如何與delegate做到這一點:

$("containing-element-selector").delegate(".UIButton a", "click", function() { 
    ... 
}); 

(這是推薦的方法)

或者與live

$(".UIButton a").live("click", function() { 
    .... 
}); 
1

這是因爲.click()功能只會影響當前存在的DOM元素。請嘗試使用.live("click", function() {your_function_here})代替。

有關更多信息,請參閱http://api.jquery.com/live/