2011-02-14 31 views
1

我有這個加載內容的腳本,然後應該綁定刪除鏈接以刪除內容。綁定與jQuery,錯誤的順序?

但是我發現它沒有與刪除鏈接綁定,即使這樣我就把代碼放在了一個應該重新綁定的函數中。

$(document).ready(function() { 


    function loadImages() { 
     $.get('/management/image/get/site_id/1/area/News', function(data) { 
      $("#existing-images").html(data); 
     }); 

     $(".deleteImage").click(function() { 
      id = $(this).attr('id'); id = id.split('_'); 
      alert(id); 
      /*$.post(second_url+'id/'+id, '', function(theResponse) { 
       $("#image_"+id+"").remove(); 
      });*/ 
     }); 
    } 


    $("#fileInput").uploadify({ 
     'uploader'  : '/library/jquery/uploadify/uploadify.swf', 
     'script'   : '/gallery/image/area/site_id/<?php echo $site->id; ?>/area/<?php echo $this->area; ?>', 
     'cancelImg'  : '/library/jquery/uploadify/cancel.png', 
     'folder'   : '/images/Image/', 
     'multi'   : true, 
     'onAllComplete' : function(e, queueId, file, response, data) { 
      $('#fileInput').uploadifyClearQueue(); 
      loadImages(); 
     }, 
    }); 


    loadImages(); 


}); 
+0

檢查你的 '刪除圖像' ID的拼寫/大寫。 – 2011-02-14 11:35:01

回答

1

您可以使用$.live函數來動態綁定刪除鏈接,而不是每次發出請求時都執行刪除鏈接。

嘗試類似:

//..init code 
$(".deleteImage").live('click',function() { 
     id = $(this).attr('id'); id = id.split('_'); 
     alert(id); 
}); 

function loadImages() { 
    $.get('/management/image/get/site_id/1/area/News', function(data) { 
      $("#existing-images").html(data); 
    }); 
} 

//more code here... 
+0

我最喜歡這個解決方案,雖然它可能會皺眉? – azz0r 2011-02-14 13:10:31

0

這是因爲ajax調用的異步性質。

你writen嘗試點擊事件還沒有被注入到DOM

試着改變你的代碼到一個按鈕綁定代碼:

$(document).ready(function() { 


    function loadImages() { 
     $.get('/management/image/get/site_id/1/area/News', function(data) { 
      $("#existing-images").html(data); 

      $(".deleteImage").click(function() { 
       id = $(this).attr('id'); id = id.split('_'); 
       alert(id); 
       /*$.post(second_url+'id/'+id, '', function(theResponse) { 
        $("#image_"+id+"").remove(); 
       });*/ 
      }); 
     }); 


    } 



    $("#fileInput").uploadify({ 
     'uploader'  : '/library/jquery/uploadify/uploadify.swf', 
     'script'   : '/gallery/image/area/site_id/<?php echo $site->id; ?>/area/<?php echo $this->area; ?>', 
     'cancelImg'  : '/library/jquery/uploadify/cancel.png', 
     'folder'   : '/images/Image/', 
     'multi'   : true, 
     'onAllComplete' : function(e, queueId, file, response, data) { 
      $('#fileInput').uploadifyClearQueue(); 
      loadImages(); 
     }, 
    }); 


    loadImages(); 
}); 

移動結合到成功調用$.get的回調確保在綁定發生之前注入了新的html。

Alternativly試圖尋找到使用delegate,而不是結合的元素,這樣你就不需要重新綁定所有的時間

1

要綁定Ajax請求完成之前刪除鏈接。