javascript - addEventListener firing automatically within loop - or only last element works -


i have loop, , creating button within each iteration. attaching event listener each newly created button, , need pass unique parameters through. please see code below (in case, passing index loop through event listener)

for (i = 0; <= worklog.worklogs.length; i++) {     if (worklog.total > 0) {         var thebutton = document.createelement("button");         thebutton.addeventlistener("click", alertbutton(i));         thebutton.innerhtml = "add";         myspan.appendchild(thebutton);     } }  function alertbutton(arg) {     return function () {         alert(arg);     }; } 

currently, event listener fires on button implemented on last iteration. if remove "return function(){}" within alertbutton function, event listener fired on each iteration without user clicking on button.

if have ideas extremely appreciative. finding other people have had problem, yet solutions provided don't seem work me. overlooking simple.

thanks!

issue in way assigning listener:

thebutton.addeventlistener("click", alertbutton(i)); 

in above code, alertbutton(i) call function , not assign it. if want pass value function assignment, should bind value.

thebutton.addeventlistener("click", alertbutton.bind(this,i)); 

as pointed @andreas, working example.

function createbuttons() {    (var = 0; < 5; i++) {      var thebutton = document.createelement("button");      thebutton.addeventlistener("click", alertbutton.bind(this, i));      thebutton.innerhtml = "add";      content.appendchild(thebutton);    }  }    function alertbutton(arg) {    console.log(arg)  }    createbuttons();
<div id="content"></div>


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -