0

The problem here is that page at alert has the final value of i.. any solution to this?

  for(var i=start;i<=end;i++)
            {
                num=pageNumber.clone();

                num.click(function(event)
                {
                    event.preventDefault();
                    var page=i;
                   alert(page);
                   // drawPager();
                });
                num.find("span").text(i);
                if(i==curPage) {
                    num.find("span").addClass("current");
                    num=num.find("span");


                }
                $("#pager>div").append(num);
            }
GorillaApe
  • 3,611
  • 10
  • 63
  • 106
  • 1
    Based on the code you've provided that is the correct behavior for the page variable. Can you tell us what you're trying to accomplish? It's hard to know the solution if we don't know the problem. – Brian Driscoll Nov 02 '10 at 15:53
  • I dont want page to be the same... – GorillaApe Nov 02 '10 at 15:55
  • possible duplicate of [How do I pass the value (not the reference) of a JS variable to a function?](http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function) – Andy E Nov 02 '10 at 16:07

2 Answers2

3

You should do something like this:

num.click(function(i) {
   return function(event) {
        event.preventDefault();
        var page = i;
        alert(page);
   }
}(i));

This would make an extra enclosure, so i wouldn't get overwritten.

bisko
  • 3,948
  • 1
  • 27
  • 29
2

You need to add the handler in a separate function that takes i as a parameter.

For example:

for(var i=start;i<=end;i++) {
    handlePage(i);
}

function handlePage(i) {
    num=pageNumber.clone();

    num.click(function(event)
    {
        event.preventDefault();
        var page=i;
       alert(page);
       // drawPager();
    });
    num.find("span").text(i);
    if(i==curPage) {
        num.find("span").addClass("current");
        num=num.find("span");


    }
    $("#pager>div").append(num);
}

This way, a separate closure (with a separate i parameter) will be generated for each function call.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964