2016-05-28 49 views
1

樣本HTML的:jQuery的 - 刪除後不工作()點擊函數用於

<div class="row" id="ThumbnailHolder"> 
    <div class="col-md-12"> 
     <img src="http://images.sportsdirect.com/images/products/16503236_pit.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l.jpg"> 
     <img src="http://images.sportsdirect.com/images/products/16503236_piat_a1.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l_a1.jpg"> 
    </div> 
</div> 

這裏是我的代碼:

$(document).ready(function() { 
    $('.Thumbnails').each(function() { 
     $(this).click(function() { 
        var BigImageLink = $(this).attr("bigimagelink"); 
        $('#ImgBigLink').attr('href', BigImageLink); 
        $('#productImgDefault').attr('src', BigImageLink); 
     }); 

    });  
}); 

此功能是偉大的工作。當我點擊類Thumbnails的一個元素,一切都會如何我需要。問題是當我執行下面的代碼部分:

$.ajax({ 
    url: 'CheckColorPrice.php', 
    type: 'POST', 
    data: { 
     url: '<?php echo $url;?>', 
     ColorId: ColorNumber, 
     ProductUrl: '<?PHP echo $ProductUrlWithoutCode;?>' 
    }, 
    dataType: 'json', 
    success: function (data) { 
      $(".Thumbnails").remove(); 
      $.each(data.thumbnails, function(index, thumbnails) {        
      $('#ThumbnailHolder div').append('<img src="http://images.sportsdirect.com/images/products/' + thumbnails + '" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/' + thumbnails + '">'); 
      }); 
    } 
}); 

我敢肯定的問題來自$(".Thumbnails").remove();,但我需要用它來Thumbnails類中刪除所有圖像,然後用新的它們是替換它們附有相同的結構和類別。當執行此代碼時,Thumbnails上的CLICK功能沒有響應。沒有任何輸出錯誤。爲什麼我的click功能不再工作?

我很肯定你可以幫助我。

在此先感謝!

+0

在javascript中必須添加類的事件處理中循環,但使用jQuery,你不需要循環。 Jquery自己做這個工作。 – Mohammad

回答

2

當前你正在使用的是被稱爲「直接」綁定,它只會在代碼進行事件綁定調用時附加到頁面上存在的元素。

您需要使用Event Delegation使用.on()委託事件方法,動態生成元件

常規語法

$(staticParentElement).on('event','selector',callback_function) 

$('#ThumbnailHolder div').on('click', '.Thumbnails', function(){  
    var BigImageLink = $(this).attr("bigimagelink"); 
    $('#ImgBigLink').attr('href', BigImageLink); 
    $('#productImgDefault').attr('src', BigImageLink); 
});