将值传递给 onclick
如果我使用循环创建大量 HTML 元素,就像
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,无论调用它的是哪个数字元素。我已经通过使用解决了这个问题
my_element.id = "something"+i;
my_element.onclick = function (e) {my_function (e.target.id)};
(显然,对于 Internet Explorer,target
需要是 srcElement
。)我很好奇是否有任何方法可以创建该函数无需像这样将 ID 添加到元素中。
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));
}
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)};
(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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
i
的值随着循环的每次迭代而变化。 您需要一个闭包来捕获的值我
:The value of
i
changes with each iteration of the loop. You need a closure to capture the value ofi
:如果您编写一个函数来构建处理函数,则可以使用新的作用域来确保获得所需的数字。例如:
If you write a function which builds you a handler function, you can use the new scope which that gives you to ensure that you get the number you want. For example:
如果我是你,我会在每个元素上使用 Jquery(或原型或任何可用的 js 框架),
你应该添加像 myid 这样的属性,以便当你单击时可以检索它。
我在我的网络应用程序上做了这个技巧:)
if I were you I will use Jquery (or prototype or whatever js frameworks that available)
on each elements you should add attributes like myid for example so that when you did on click you can retrive it.
I did this trick on my web app :)