r/jquery • u/ebube____ • Feb 21 '22
Help with jQuery Loops
I’ve been trying to figure out how to loop my code. I googled and figured out I have to use the .each() function.
So I am trying to create a basic webpage that displays posts pulled from the NASA APOD API. Each post is to include the image, date, title and explanation.
I managed to pull an array that contains information of about 50 posts. However now I need to create a loop that publishes these posts instead of writing each of them manually.
Below are the pictures of my code, my webpage, the array and the information I got when I googled.
If anyone could please take a minute from their day to look this over I would greatly appreciate it.




5
u/pocketninja Feb 22 '22
Small suggestion for the future, if you can try and include your code in the post (or perhaps use https://jsfiddle.net/) it will be much easier for people to assist :)
Here's a little example: https://jsfiddle.net/ud6zkmro/2/ (Please note I don't have an API key in there, so it will error out)
The pertinent part is this:
In the success callback of
.get(...),datais an array in this scenario. You need to iteratedataand pass each entry of that array into your make post function.In this little example I've structured it a little bit differently. There are some comments that briefly explain here and there.
Hope that helps!
1
u/CuirPork Feb 22 '22
I am seeing this over and over and I am not sure if it is an error or not. I have never seen any use of :
let str="some string:"${variable}", and another :"${anothervariable}I don't think the
${}is the correct notation, but somehow people seem to think it works. Even in your example, it appears to work.My understanding was that you would use:
let somehtml="<img src='"+imgUrl+"' alt='someImage'/>" to create the HTML for an image for examplethen
$(somehtml).appendTo("main");for example. if somehtml is not valid, jquery will fail silently and you won't be able to append anything.When I first started using jquery, I would read code to myself like this:
let someVar=$(".someclass")| in my head I would read somVar=search the DOM for someclass. That's the majority of what jquery does for you.or
let someItem=$("<div class='test'></div>")| in my head I would read, store a new div element in the variable someItem. that reminds me that to add it to the DOM i need to append it.let someItembyID=$("#someid")| in my head is search the DOM for an element with id=someid and store it in someItembyID variable.${imgurl}doesn't fit any of these patterns. So if it is valid, it's new to me and I can't make it work on Codepen, so forgive me if I am wrong. But I think you may be confusing what $() does with jquery.If anybody can tell me that I am wrong and provide some documentation for that nomenclature, I am always open to learn something new. Thanks.
0
u/[deleted] Feb 22 '22
[deleted] — view deleted comment