Javascript Array addEventListener

前端 未结 2 906
闹比i
闹比i 2021-01-06 11:52

Interactive map with buttons in the shape of states, each button has the state abbreviation as an id, when a button/state is clicked I would like to fire the function \"stat

2条回答
  •  一生所求
    2021-01-06 12:43

    Because when the handler runs, it looks up the value of i, which is wherever it was after the loop finished.

    You need to scope the i variable in a function:

    function listenerForI( i ) {
        document.getElementById(stateList[i]).addEventListener('mousedown', function() {stateSelect(stateList[i])}, false);
    }
    for (var i = 0; i < stateList.length; i++) {
        listenerForI( i );
    }
    

    Now the i referenced by the handler will be the parameter to the listenerForI function that was invoked. As such, that i will reference the value that was passed in from the for loop.

提交回复
热议问题