Reputation: 127
So, I'm following a tutorial where we are making a youtube search engine that will display some videos from youtube. This was the first video where the instructor mentioned the each loop. I looked on JQuery documentation but still cant wrap my head around what exactly this each loop is trying to do. I was following well with the instructor until he brought in the each loop near the end of the code below. I'm not too sure what the instructor is doing with this loop. Any insight would be helpful
function search()
{
$('#results').html('');
$('#buttons').html('');
// get form input
q = $('#query').val();
//run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search",{
part:'snippet,id',
q:q,
type: 'video',
key:'AIzaSyCadgai_XAKk2TYQH1f5lXrR5QEHWXowfA'
},
function(data)
{
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log data
console.log(data);
$.each(data.items,function(i,item))
{
var output = getOutput(item);
$('#results').append(output);
}
}
);
}
Upvotes: 1
Views: 70
Reputation: 11116
By looking at the code, I can tell that the response that you are getting back from the ajax call is an object. Said object has a property called items. Since the instructor is "foreaching" the items property, I can conclude that it is an array. Therefore, the .each()
is iterating over every item in the data.items array to perform an action on each of them.
Now, you have not included the code for the getOutput()
function, but based on the rest of the code, I can see that it is generating HTML markup using the current item in the .each()
loop. After getting the HTML markup from getOutput()
, it is appending the HTML to an element with the id="results" which will display it on the screen (assuming the results element is visible).
Hope that helps you understand what it's doing!
Upvotes: 0
Reputation: 218950
It's basically just a loop, but using the jQuery function syntax. The benefit of that syntax is when you want to loop over a selected set of DOM elements, since the core of jQuery's usefulness is the simplicity with which is queries the DOM. While it also works for any collection, it's not always necessary (unless you just want to use the syntax for consistency).
.each()
simply iterates over the elements it's given, invoking the supplied function on each one. Within the function, i
is the index (0 through the element count minus 1) and item
is the current element. (And those two parameters can be named whatever you like, to keep your code clear and understandable.)
Basically, this:
$.each(data.items,function(i,item))
{
var output = getOutput(item);
$('#results').append(output);
});
is reasonably similar to this:
for (var i = 0; i < data.items.length; i++) {
var output = getOutput(data.items[i]);
$('#results').append(output);
}
Upvotes: 1