Steven Luo
Steven Luo

Reputation: 2538

Javascript dynamically create elements and onclick functions

I need to do the following things:

Here's the code

var i = 0;
for(path of paths) {
  i++;
  $("#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?

Thanks.

Upvotes: 0

Views: 46

Answers (2)

Dominique Fortin
Dominique Fortin

Reputation: 2238

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.

Upvotes: 0

ThisMan
ThisMan

Reputation: 290

You can use closure

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

Upvotes: 1

Related Questions