Javascript Array addEventListener

前端 未结 2 908
闹比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:26

    You have a scoping issue. Javascript is not block-scoped; it is function-scoped. Basically, you must create a new function whenever you wish to create a new variable in a loop.

    The most elegant way to do so is as follows:

    stateList.map(function(abbrev){
        $(abbrev).mousedown(function(){stateSelect(abbrev)});
    });
    

    If you are not using jQuery, merely replace $(abbrev).mousedown with document.getElementById(abbrev).addEventListener.

    (Just to preempt the people who go "map isn't standard"; it is in the javascript ECMA-262 standard 5th edition which has support from all browser vendors. If one is paranoid about supporting older browsers, one can just $.map.)

    Here is how one would do so using a for loop; it's a bit uglier but it demonstrates the necessity of creating new closures via functions:

    for(var i=0; i

    Like I said, a bit uglier than necessary; you could also do this which is slightly less ugly, but is basically the same thing:

    function createListener(abbrev) {
        $(abbrev).mousedown(...);
    }
    for(var i=0; i

提交回复
热议问题