javascript - JS onclick event from loop -


this question has answer here:

i have problem javascript , onclick event. want define onclick event element created in loop. code looks somehow this:

for (var = 0; < 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, code creates event listener this:

listenerbody: "function () {addfeed(entry.title, entry.url); backbutton();}" 

but need value of entry.title , entry.url like:

listenerbody: "function () {addfeed('abc', 'http://example.com'); backbutton();}" 

i hope can me.

you hit against thing in javascript called hoisting , closure looping.

what happening loop continues, , when onclick function triggered, have in entry variable last element of result.entries.

to solve can lock in closure (example):

function setonclickevent(element, entryvalue) {   element.onclick = function () {     addfeed(entryvalue.title, entryvalue.url);     backbutton();   }; }  (var = 0; < result.entries.length; i++) {   var entry = result.entries[i];   var adder = document.createelement('span');   adder.innerhtml = '+';   setonclickevent( adder, entry)   container.appendchild(adder); } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -