将值传递到onclick [英] Passing values to onclick
问题描述
如果我使用循环创建了大量的HTML元素,例如
If I create a whole lot of HTML elements using a loop, like
for (i= 1; i < 100; i++) {
var my_element = document.createElement ("td");
row.appendChild (my_element);
my_element.onclick = function () {my_function (i));
}
那么当元素被点击时,i的值传递到 my_function
总是100,无论什么数字元素调用它。我已经解决了这个问题,使用
then when the element is clicked, the value of i passed to my_function
is always 100, regardless of what number element is calling it. I have worked around this by using
my_element.id = "something"+i;
my_element.onclick = function (e) {my_function (e.target.id)};
(对于Internet Explorer,目标
需要显然是 srcElement
。)我很想知道是否有任何方法来创建函数,而不必像这样将元素添加到ID。
(For Internet Explorer, the target
needs to be srcElement
, apparently.) I am curious to know whether there is any way to create the function without having to add the ID to the element like this.
推荐答案
i
的值随着循环的每次迭代而更改。 您需要一个闭包来捕获<$ c的值$ c> i :
The value of i
changes with each iteration of the loop. You need a closure to capture the value of i
:
(function(i) {
my_element.onclick = function () {my_function (i)};
}(i))
这篇关于将值传递到onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!