javascript - jQuery - click function not working after remove() is used -
sample of html:
<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>
here code:
$(document).ready(function() { $('.thumbnails').each(function() { $(this).click(function() { var bigimagelink = $( ).attr( "bigimagelink" ); $('#imgbiglink').attr('href', bigimagelink); $('#productimgdefault').attr('src', bigimagelink); }); }); });
this function working great. when click element class thumbnails
goes how need. problem comes when execute following part of code:
$.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 + '">'); }); } });
i pretty sure problem comes $( ".thumbnails" ).remove();
need remove images class thumbnails
, replace them new ones appended same structure , class. when code executed click function on thumbnails
not responding. there no output errors ot ever. why click
function not working anymore ?
i pretty sure can me this.
thanks in advance!
currently using called "direct" binding attach element exist on page @ time code makes event binding call.
you need use event delegation using .on() delegated-events approach, when generating elements dynamically.
general syntax
$(staticparentelement).on('event','selector',callback_function)
example
$('#thumbnailholder div').on('click', '.thumbnails', function(){ var bigimagelink = $( ).attr( "bigimagelink" ); $('#imgbiglink').attr('href', bigimagelink); $('#productimgdefault').attr('src', bigimagelink); });
Comments
Post a Comment