如何在Javascript中使用循环生成事件处理程序? [英] How to generate event handlers with loop in Javascript?
本文介绍了如何在Javascript中使用循环生成事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有10个从AJAX响应生成的标签:
For example, I have 10 a tags generated from an AJAX response:
<a href="#" id="b1">b1</a>
<a href="#" id="b2">b2</a>
<a href="#" id="b3">b3</a>
<a href="#" id="b4">b4</a>
<a href="#" id="b5">b5</a>
<a href="#" id="b6">b6</a>
<a href="#" id="b7">b7</a>
<a href="#" id="b8">b8</a>
<a href="#" id="b9">b9</a>
<a href="#" id="b10">b10</a>
我需要通过循环为每个人分配onclick事件:
I need to assign onclick event to each of them via loop:
for(i=1; i<11; i++) {
document.getElementById("b"+i).onclick=function() {
alert(i);
}
}
这不起作用,它只分配onclick到最后一个标签并提醒11。我怎样才能让它发挥作用?我不想使用jQuery。
This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.
推荐答案
所有处理程序共享相同的 i
变量。
All of your handlers are sharing the same i
variable.
您需要将每个处理程序放入一个单独的函数,该函数将 i
作为一个参数,以便每个人获得自己的变量:
You need to put each handler into a separate function that takes i
as a parameter so that each one gets its own variable:
function handleElement(i) {
document.getElementById("b"+i).onclick=function() {
alert(i);
};
}
for(i=1; i<11; i++)
handleElement(i);
这篇关于如何在Javascript中使用循环生成事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文