Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kyle Vassella
9,033 PointsjQuery .each() method
I'm using jQuery to implement pagination.
Online I found a very short, simple way to do this. I've tested it and it works (displays no more than 10 items per page), but I do not fully understand it yet:
var pageSize = 10;
var showPage = function(page) {
$(".content").hide();
$(".content").each(function(n) {
if (n >= pageSize * (page - 1) && n < pageSize * page)
$(this).show();
});
}
showPage(1);
$("#pagin li a").click(function() {
$("#pagin li a").removeClass("current");
$(this).addClass("current");
showPage(parseInt($(this).text()))
});
The part that is confusing me is the event handler inside of .each(). I'm curious as to what the n represents. Does this represent the index? Does n simply work as a counter? And the reason it works as a counter is due to the jQuery library making it work this way? That's my best guess for now. Hoping someone can confirm or elaborate.
2 Answers
Steven Parker
243,253 Points
The n represents the item index.
This is explained in the JQuery API page for .each. The function is called for every element that was selected and the argument indicates the item's index in the collection. And this represents the element itself.
Kyle Vassella
9,033 PointsThanks Steven. I think I didn't realize on that api page that 'index' is simply a placeholder and really anything can be written there to represent it. My only other question would be the following math:
if (n >= pageSize * (page - 1) && n < pageSize * page)
When I break it down and plug an index value into n it makes sense and works. My concern is that if I were on my own, I don't think I'd be able to think up this math on my own. Sure, in this case and others I technically didn't need to since I can just look it up. But how does one get to the point where you can just think problems out in this way? I'm sure writing the problem out as a plan, as Andrew Chalkley teaches, would help. But I don't think I'm there yet. Does this just come with time? Should I try my best right now to be able to think up and write math operations like this on the fly, or is my time more efficiently spent 'looking it up online' at this point?
AKA how important is that ability? (to think up and write math operators like that on the fly)