views:

2717

answers:

4

Hi,

I currently have the following in JQuery 1.3.2

for (i = 0; i < totalPages; i++) {
   var newDiv = $("<a href=\"#\">").append(i+1).click(function() 
   { 
      alert(i+1);
   });
   $('#pageLinks').append(newDiv).append(" ");
}

This outputs a list of numbers as required, but the alert when clicking the generated element is returning the totalPages value, not the value of i during the loop. How do I get the click event to alert the value of i instead?

Thanks

+3  A: 

Try this

for (i = 0; i < totalPages; i++) {
   var newDiv = $("<a href=\"#\">").append(i+1).click(function() 
   { 
      alert(this.text);
   });
   $('#pageLinks').append(newDiv).append(" ");
}
DanSingerman
A: 

This code should sort your problem out:

for (i = 0; i < totalPages; i++) {
    var newDiv = $("<a href=\"#\">")
        .append(i+1)
        .click(
            function() { 
                alert($(this).html());
            }
         );
    $('#pageLinks').append(newDiv).append(" ");
}
pmckenna
A: 

This is a scope related problem. You need to form a closure around the statements in the for loop using, what I call a scope guard. Something like this:

var totalPages = 10;
for (i = 0; i < totalPages; i++) {
    (function() {
        var no = i + 1;
        var newDiv = $("<a href=\"#\">").append(i+1).click(function() {
        alert(no);
    });
    $('#pageLinks').append(newDiv).append(" ");
})();
Helgi
A: 

If, say, you didn't have the text of the number as part of the link, I like to encode values like this into the id, which would give you this:

<body>
<div id="pageLinks"><!-- --></div>

<script>
var totalPages = 10, newDiv;
for (i = 0; i < totalPages; i++) {
  var link = "<a href=\"#\" id=\"link-"+(i+1)+"\">"+(i+1)+"</a>";
  newDiv = $(link).click(function() {
    alert($(this).attr('id').split('-')[1]);
  });
  $('#pageLinks').append(newDiv).append(' ');
}
</script>
</body>
artlung