Passing parameter onclick, in a loop

前端 未结 2 1135
轻奢々
轻奢々 2021-01-15 14:04

Im creating input elements in a loop. On click, these buttons are supposed to call a certain function with a certain Parameter, based on the Initial creation of the button e

相关标签:
2条回答
  • 2021-01-15 14:29

    You need to use an IIFE and create a new closure like

    for (var i = 0; i < planets.length; i++){
      var id = planets[i].id;
    
      var input = document.createElement("input");
      input.type = "button";
      input.className = "worldButton";
      input.value = "Choose this world";
      
      input.onclick = (function(id, planets){
         return function(){
             game.pickWorld(planets, id);
         }
      })(id,planets);
    }
    

    What was happening is the variables planets and id were visible to the callback function and at execution time, were using the last iterated value.

    However, with a closure, you effectively created a 'private' variable seen and preserved by each callback function.

    0 讨论(0)
  • 2021-01-15 14:53

    You need to pass the id and planets variables in the function like:

    for (var i = 0; i < planets.length; i++){
      var id = planets[i].id;
    
      var input = document.createElement("input");
      input.type = "button";
      input.className = "worldButton";
      input.value = "Choose this world";
      Input.onclick = (function(pl, id){
         game.pickWorld(pl, id);
      })(planets, id);
    }
    

    You can read more about IIFE in this article.

    0 讨论(0)
提交回复
热议问题