在循环中传递参数onclick [英] Passing parameter onclick, in a loop

查看:160
本文介绍了在循环中传递参数onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在循环中创建输入元素。
单击时,这些按钮应该根据按钮元素的初始创建调用具有特定参数的特定函数。
实际上发生的事实是所有按钮总是使用LAST按钮中的参数调用该函数。

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 element. What in fact does happen is that all Buttons always call the function with Parameter from the LAST button.

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(){
     game.pickWorld(planets, id);
  }
}

每个按钮似乎总是传递行星的id [planets.length]而不是 planets [i]
console.log(id)是正确的。
使用 onclick addEventListener jquery.click <无关紧要code>。

Each button always seems to pass on the id of planets[planets.length] instead of planets[i]. console.log(id) is correct. It doesnt matter if use onclick, addEventListener or jquery.click.

然而,整个行星数组成功传递。

The whole planets Array however is passed on successfully.

我怎样才能得到输入正确传递特定迭代的id?

How can i get the Input to correctly pass on the id of that particular Iteration ?

推荐答案

你需要使用 IIFE 并创建一个新的闭包,如

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);
}

发生的变化是行星 id 对回调函数可见,并且在执行时使用最后一个迭代值。

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.

这篇关于在循环中传递参数onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆