Javascript dynamically create elements and onclick functions

I need to do the following things:

  • First, fetch data paths on a server. The data contains an array of path and the length is unknown.

  • Then I create a list-group where each list-group-item stands for a path.

  • Finally, I set the click function of each of the list-group-item which displays the correponding path in the data array.

Here's the code

var i = 0;
for(path of paths) {
  $("#list_path").append('<a id="list-path-' + i + '" class="list-group-item tooltip-button"">' + "Path " + i + '</a>');
  $("#list-path-" + i).click(function() { console.log(path) })

However, no matter which list-group-item I click, only the last path element is shown. I guess the problem is that only a pointer of path is assigned to the click function, which in the end of the for loop, always points to the last path.

How can I set the click function to display different path?


Answers 1

  • You have to do this

    $("#list-path-" + i).click(function() { console.log($(this).text()); })

    Because of closure, path is the last value of the for loop.

Related Articles