-1

I have the following which i seem to be repeating a lot of the same code.

        $('.announcementsTitle1').prepend(response.posts.data[0].name);
        $('.announcementsTitle2').prepend(response.posts.data[1].name);
        $('.announcementsTitle3').prepend(response.posts.data[2].name);
        $('.announcementsTitle4').prepend(response.posts.data[3].name);
        $('.announcementsTitle5').prepend(response.posts.data[4].name);

        $('.announcementsText1').prepend(response.posts.data[0].message);
        $('.announcementsText2').prepend(response.posts.data[1].message);
        $('.announcementsText3').prepend(response.posts.data[2].message);
        $('.announcementsText4').prepend(response.posts.data[3].message);
        $('.announcementsText5').prepend(response.posts.data[4].message);

        $('.announcementsText1').append(response.posts.data[0].description);
        $('.announcementsText2').append(response.posts.data[1].description);
        $('.announcementsText3').append(response.posts.data[2].description);
        $('.announcementsText4').append(response.posts.data[3].description);
        $('.announcementsText5').append(response.posts.data[4].description);

        $('.announcementsImage1').attr("src",response.posts.data[0].full_picture);
        $('.announcementsImage2').attr("src",response.posts.data[1].full_picture);
        $('.announcementsImage3').attr("src",response.posts.data[2].full_picture);
        $('.announcementsImage4').attr("src",response.posts.data[3].full_picture);
        $('.announcementsImage5').attr("src",response.posts.data[4].full_picture);]

Is there a way i could refactor something like this?

Ma9ic
  • 1,107
  • 4
  • 16
  • 30

2 Answers2

1

Loop?

for (i=0;i<=4;i++) {
    $('.announcementsTitle'+(i+1)).prepend(response.posts.data[i].name);
    $('.announcementsText'+(i+1)).prepend(response.posts.data[i].message);
    $('.announcementsText'+(i+1)).append(response.posts.data[i].description);
    $('.announcementsImage'+(i+1)).attr("src",response.posts.data[i].full_picture);
}
lpg
  • 4,897
  • 1
  • 16
  • 16
1

JQuery.each

   $.each(response.posts.data, function(index){

        $('.announcementsTitle'+index).prepend($(this).name);
        $('.announcementsText'+index).prepend($(this).message);
        $('.announcementsText'+index).prepend($(this).description);
        $('.announcementsImage'+index).attr("src",$(this).full_picture);

    });
Victor Levin
  • 1,167
  • 6
  • 11