2014-10-09 51 views
1

我想加載一個文件夾中的所有圖像到一個div(id =「wrap」)但它是點擊功能不工作。爲什麼?動態創建的圖像的onclick()不工作

以下是我的代碼。

<script> 
    $(document).ready(function() { 

     var folder = 'images/print/thumb/' 
     post_data = {'folder':folder}; 

     $.post('get_images.php', post_data, function(images){ 
      for (var i = 0; i < images.length; i++) { 

       var tag = '<img class="thumb" src="' + folder + images[i] + '" />'; 

       $("#wrap").prepend(tag); 
      } 

     }, 'json'); 

     $(".thumb").click(function(){ 
      alert(this.id); 
     }); 

    }); 
</script> 

<body> 
    <div id="wrap" style="padding:20px;"> 
    </div> 
</body> 

它完美地加載圖像。唯一的問題是點擊事件。

回答

2

嘗試把事件註冊的Ajax調用背部的內側部分,

$.post('get_images.php', post_data, function(images) { 

     for (var i = 0; i < images.length; i++) { 
     var tag = '<img class="thumb" src="' + folder + images[i] + '" />'; 
     $("#wrap").prepend(tag); 
     } 

     $(".thumb").click(function(){ 
      alert(this.id); 
     }); 

}, 'json'); 

還是最好的辦法是使用event delegation

$("#wrap").on("click", ".thumb", function(){ 
    alert(this.id); 
});