Event handler scope in Javascript

后端 未结 3 1342
臣服心动
臣服心动 2021-01-14 10:03

This is probably an easy question but I can\'t figure out the best answer for it.

I have 10

elements on screen. Each of them has a cli
3条回答
  •  无人共我
    2021-01-14 10:15

    You only have one variable i in an outer scope shared by all your click handlers. You need to create a local variable i for each closure. This will work:

    for ( var i = 0; i < 10; i++ ) {
        var element = document.getElementById( "element" + i );
        element.onclick = (function(i){
            // returns a new function to be used as an onclick handler
            return function () {
                alert( "Element " + i );
            }
        })(i); // Pass in the value of the outer scope i
    }
    

    Check "The Infamous Loop" problem in this article (and read the whole artice) for more information :)

提交回复
热议问题