1

I have a problem with JavaScript and the onclick event. I want to define the onclick event from an element I created in a loop. My code looks somehow like this:

for (var i = 0; i < result.entries.length; i++) {
  var entry = result.entries[i];
  var adder = document.createElement('span');
  adder.innerHTML = '+';
  adder.onclick = function () {
    addFeed(entry.title, entry.url);
    backButton();
  };
  container.appendChild(adder);
}

The problem is, that this code creates an event listener like this:

listenerBody: "function () {addFeed(entry.title, entry.url); backButton();}"

But I need the value of entry.title and entry.url like:

listenerBody: "function () {addFeed('ABC', 'http://example.com'); backButton();}"

I hope someone can help me.

Dirk
  • 436
  • 2
  • 15

1 Answers1

0

You just hit against a thing in javascript called hoisting and closure looping.

What is happening is that your loop continues, and when the onclick function is triggered, what you have in the entry variable is the last element of result.entries.

To solve this you can lock it in a closure (example):

function setOnClickEvent(element, entryValue) {
  element.onclick = function () {
    addFeed(entryValue.title, entryValue.url);
    backButton();
  };
}

for (var i = 0; i < result.entries.length; i++) {
  var entry = result.entries[i];
  var adder = document.createElement('span');
  adder.innerHTML = '+';
  setOnClickEvent( adder, entry)
  container.appendChild(adder);
}
fmsf
  • 36,317
  • 49
  • 147
  • 195