views:

77

answers:

2

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!.

+4  A: 

Instead of referencing the pageNum variable directly, just get it dynamically from each link, for example:

$('#page' + pageNum).click(function(){
   alert(this.id.replace('page',''));
});

Or give them a class, say .pageLink and bind them all at once, like this:

$('.pageLink').click(function(){
   alert(this.id.replace('page',''));
});

Currently you're referencing a single pageNum variable 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:

$('#page' + pageNum).bind({id: pageNum}, 'click', function(e) {
   alert(e.data.id);
});
Nick Craver
For some reason the 3rd option didn't work, which is more what I was trying to figure out, but regardless I simply used the id like you showed here in the click event.Thanks!
Munzilla
A: 
$('#page' + pageNum).click(function()
{
  var pageNum = $( this ).attr( 'id' ).match(/page([0-9]*)/)[1];

  alert( pageNum );
});
ovais.tariq