JavaScript closure issue on dynamic element creation in a loop -


during execution of page, string gets composed containing code need executed handler click event. string like:

var handler = '"myfunction1(12, 20);myotherfunction();"'; 

or

var handler = '"myfunction1(12, 20);"' 

when create buttons dynamically, , try attach events in loop, gets attached last button only. can sense closure issue missing?

here code.

var buttons = [], arg1 = 12, arg2 = 20;  var butt1 = { text: 'bye', onclick: "anotherfunction();" }, butt = { text: 'hello', onclick: "mynewfunction();" }, butt2 = { text: 'bye333' };  buttons.push(butt1); buttons.push(butt); buttons.push(butt2);   function mynewfunction() {    alert('my new  function'); };  function myclosefunction(arg1, arg2) {     alert('close: ' + arg1 + ' other: ' + arg2) }  function anotherfunction() {     alert('say goodbye'); }   window.onload = function () {  var buttoncontainer = document.getelementbyid('controldiv'),     closeonclick = "myclosefunction(" + arg1 + ", " + arg2 + ")",     button;  (var = 0; < buttons.length; i++) {     buttons[i].onclick = (buttons[i].onclick == null) ? closeonclick : (closeonclick + ';\n' + buttons[i].onclick);     button = document.createelement("input");     button.type = 'button';     button.onclick = new function(buttons[i].onclick);      if (i > 0)         buttoncontainer.innerhtml += '&nbsp';     buttoncontainer.appendchild(button);    } }; 

the html page simple:

<!doctype html>  <html lang="en"> <head>     <meta charset="utf-8" />     <title></title>     <script src="script.js" type="text/javascript"></script> </head> <body>     <h1>hello</h1>     <div id="controldiv"></div> </body> </html> 

sensing closure issue have tried various options close on variables not successful. e.g.

button.onclick = (function (action, i) {     var name1 = 'hello' + i,         a123 = new function('action', 'return function ' + name1 + '(){action();}')(action);         return a123;     } (new function(buttons[i].onclick), i)); 

buttoncontainer.innerhtml += '&nbsp'; - line (or rather re-setting innerhtml) problem. don't think innerhtml property contains events. works expected here.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -