2011-12-31 34 views
2

工作我使用jQuery(1.6.2)的舊版本,似乎無法獲得委託的工作。我有一個列表,我試圖用一個單擊事件委託,但它重新加載列表後失敗。jQuery的委託不具有列表項

這裏是我當前的代碼:

$(".image_result").delegate("li", "click", function() { 

//$('.image_result li').click(function() { 
    var imgInfo = $(this).attr('id').split(':'); 

    if(confirm('Are you sure you want to delete this image?')) { 
     $.post('delete_image.php?image_id=' + imgInfo[0] + '&user_id=' + imgInfo[1], function(data) { 

      if (data.st) { 
       var resp = data.html.split("|"); 

       $('#imageStats').html(resp[0]); 
       $('#imageTable').html(resp[1]); 
      } 
      else { 
       alert("Yikes, something went wrong"); 
      } 
     }, "json"); 
    } 
}); 

的imageTable格設置現在擁有新的列表項(image_result)

我缺少什麼?

+0

你可以張貼HTML結構以及 – frictionlesspulley 2011-12-31 02:59:47

+0

當你重新加載列表,你清理掉,並重新建立LIS,或者是你破壞並重新創建.image_result元素? – 2011-12-31 03:01:57

回答

4

.delegate()的關鍵是你不能銷燬/替換jQuery對象中的項目(在這裏是.image_result。這樣做會殺死你的jQuery事件處理程序。你在jQuery對象中使用的選擇器必須是靜態的。破壞或更換)

在你的情況,並假設.image_result#imageTable一個孩子,你也許可以用這個來代替:

$("#imageTable").delegate(".image_result li", "click", function() {...}); 

因爲#imageTable是沒有得到更換所以它的事件處理程序生存更改子對象和th e選擇器作爲參數傳遞給.delegate()零在右邊的li對象。

+0

這是問題所在。在父分區工作的設置代理。我沒有意識到這一點。非常感謝...我每天都會學到東西:) – Paul 2011-12-31 03:06:02