JavaScript closure issue on dynamic element creation in a loop
<p>During the execution of the page, a string gets composed containing the code that would need to be executed as the handler for the click event. The string could look like:</p>

<pre><code>var handler = '"myFunction1(12, 20);myOtherFunction();"';
</code></pre>

<p>OR</p>

<pre><code>var handler = '"myFunction1(12, 20);"'
</code></pre>

<p>When I create the buttons dynamically, and try to attach the events in a loop, it gets attached to the last button only. I can sense a <b>closure</b> issue but what am I missing?</p>

<p>Here is the code.</p>

<pre><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;

for (var i = 0; i &lt; 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 &gt; 0)
        buttonContainer.innerHTML += '&amp;nbsp';
    buttonContainer.appendChild(button);
   }
};
</code></pre>

<p>The HTML page is simple: </p>

<pre><code>&lt;!DOCTYPE html&gt;

&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="utf-8" /&gt;
    &lt;title&gt;&lt;/title&gt;
    &lt;script src="Script.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;hello&lt;/h1&gt;
    &lt;div id="controlDiv"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Sensing a <strong>closure</strong> issue I have tried various options to close over any variables but was not successful. e.g.</p>

<pre><code>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));
</code></pre>
