This is probably something simple but it’s driving me nuts.
I’m making some pagination using jquery and a while loop which has a variable called “pageNum” that updates at the end of the loop and represents the page being written out. Obviously pageNum is added to at the end of each iteration. Fine.
Here’s the code that’s giving me a hard time:
$('#page' + pageNum).click(function(){
alert(pageNum);
});
So that id works properly and will assign a click even to (for example) a span with an id of page3 if 3 is the current pageNum. The problem is, when I click on that span, the pageNum that is alerted is always the last value of pageNum that was set in the loop. So if there’s 8 pages, it will always alert 8. So, I figured it must be always pulling in the current value, so I tried passing pageNum in like this:
$('#page' + pageNum).click(function(pageNum){
alert(pageNum);
});
But now the alert shows [Object object].
I’ve tried creating variables inside and out of the click event and assigning them the value of pageNum and nothing seems to work.
This must be something really stupid, can someone please help me out? I need to have the current pageNum usable within that click event.
Thanks in advance for your help!.
Instead of referencing the
pageNumvariable directly, just get it dynamically from each link, for example:Or give them a class, say
.pageLinkand bind them all at once, like this:Currently you’re referencing a single
pageNumvariable from your loop which changes and ends up whatever it was at the end of the loop. You either need to pass it in a closure or ignore it altogether, like above, or use event data passed to.bind(), like this: