Richard Garfield Richard Garfield - 1 year ago 68
JSON Question

How to pass int via eventListener in Javascript?

I generate a list of Magic cards from a Json file.

for (i in {
leftCardElement = document.createElement("p");
leftCardElement.innerHTML =[i].points + " " +[i].name + "&nbsp";
leftCardElement.addEventListener("click", leftCardClicked);

function leftCardClicked(event) {// access card.cost and other things }

The problem is that when the
method is called I'd like to be able to have access to the[i]
object. The
object seems to refer to the element that I clicked on inside of
. Is there some way that I can pass the index
to the event handler so I can get my card object?

Answer Source

Same like @AlejandroC but without the dependency on the i (this i will change on each iteration) , therefore I clone it before passing, using with Object.assign()

In your for loop do:

leftCardElement.addEventListener("click", leftCardClicked.bind(this, Object.assign({},[i]));

then your function should be:

function leftCardClicked(card, event) { ... }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download