0

Below is my script for getting optimized image through javascript.

<img data-src='a.jpg'>
<img data-src='b.jpg'>
<img data-src='n.jpg'>


<script>
    $('img').each(function(){
        var datasrc = $(this).data('src');
        $.get('api.php',{"dataa":datasrc},function(result){
            $(this).attr('src',result));
        })
    });
</script>

Anyway, 'result' returns optimized images, but the $(this) src not updating. The src shows unknown

What is wrong here? May be $(this) does not work inside $.get callback function ?

Please help me

Learner
  • 3
  • 3

1 Answers1

0

I think indeed the second $(this) refers to the this of the call, not the image. You can try:

$('img').each(function(){
    const image   = $(this),
          datasrc = image.data('src');

    $.get('api.php',{"data":datasrc}, function(result) {
        image.attr('src',result));
    });
});
arvie
  • 742
  • 1
  • 5
  • 9