将值传递给 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));
}
然后当元素被点击时,传递给 my_function
的 i 的值总是 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,target
显然需要是 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
的值随着循环的每次迭代而变化.您需要一个闭包来捕获 的值我
:
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屋!