开发者

attach function with parameter from javascript

开发者 https://www.devze.com 2023-01-05 07:14 出处:网络
I have this function: function addButtonLookup() { var element = document.getElementById(\"btnToolBar\");

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消