tags:

views:

36

answers:

1

I have this function:

function addButtonLookup() {

    var element = document.getElementById("btnToolBar");
    var index;
    for (var i = 0; i < lookupArray.length; i++) {

        index = i;

        var btn = document.createElement('input');
        btn.type = 'button';
        btn.value = '' + lookupArray[i];
        btn.name = 'btnLookup' + i;
        btn.id = i;
        btn.className = 'CommonButtonStyle';
        element.appendChild(btn);
        btn.onclick = function() {
            debugger;

            tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
        };


    }

}

onbutton click the i is undefined

+2  A: 

Instead of this:

btn.onclick = function() {
    debugger;

    tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
};

Try this:

btn.onclick = (function(i) {
    return function() {
        debugger;
        tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
    }
})(i);

The issue with the first version is that the i variable is copied from the current scope. However the i variable varies in the current scope (it's part of a for loop), this is why you're getting this weird behavior.

By passing the i variable as a paremeter to a new function (like the second example) the current i variable is copied.

You should take a look at how Closures work in JavaScript.

Luca Matteis