-1

Creating list of links dynamically using jquery, and wanted to bind separated click event's to each of them.

for (var i = 0; i < 7; i++) {
    var li = $('<div>').addClass('text-primary').css("curser", "pointer").appendTo($("#AK_test"));
    var aleg = $('<a>').addClass('pull-left text-primary').css('color','#337ab7').text(" Clickable link # " + i);

    aleg.on("click", function() {
        alert("clicked # " + i);
    });
    aleg.appendTo(li);
    $('<br>').appendTo(li);
}
<div id="AK_test"></div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js?ver=4.1'></script>

In this example alert always shows 7 (last value of i).

My Question: Why? For each link it should show separate value of i in alert.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
ArunK
  • 67
  • 2
  • 10
  • Welcome to Stack Overflow! The full content of your question must be **in** your question, not just linked. Links rot, making the question and its answers useless to people in the future, and people shouldn't have to go off-site to help you. Put a [mcve] **in** the question, ideally using Stack Snippets (the `<>` toolbar button) to make it runnable. More: [*How do I ask a good question?*](/help/how-to-ask) – T.J. Crowder Jul 24 '16 at 10:50
  • 2
    From your description, this is likely a duplicate of [*JavaScript closure inside loops – simple practical example*](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – T.J. Crowder Jul 24 '16 at 10:51

1 Answers1

0

Thanks to T.J. Crowder, for finding the original solution.

Here is same fix to -my problem code in this question-

  for (var i = 0; i < 7; i++) {
      var li = $('<div>').appendTo($("#AK_test"));
      var aleg = $('<a>').css('color','#337ab7').text(" link # " + i);

      aleg.on("click", createClickEvent(i));
      aleg.appendTo(li);
      $('<br>').appendTo(li);
  }
  function createClickEvent(i) {
      return function() { alert(i); };
  }
  <div id="AK_test"></div>
ArunK
  • 67
  • 2
  • 10