一个循环中的Javascript绑定点击手柄 [英] Javascript binding click handller inside a loop
问题描述
我正在尝试创建几个链接,并在一个循环中绑定一个onclick handller。点击链接时,我想显示一个提示框,指示链接号(第一个链接为1,第二个链接为2,第二个链接为3,等等)。
I'm trying to create several links and bind an onclick handller to them inside a loop. On clicking the link, I want to display an alert box which indicates the link number (1 for 1st link, 2 for second link, 3 for second link and so on).
<html>
<body>
</body>
</html>
<script type = 'text/javascript'>
for (var i = 0; i < 10; i++) {
var link = document.createElement("a");
link.innerHTML = "Link " + i;
link.href = '#';
link.onclick = function () {
alert("This is the link " + i);
return false;
};
document.body.appendChild(link);
}
</script>
由于某种原因,我可以点击相同的提醒信息这是链接10在任何链接上。
For some reason, I get the same alert message "This is the link 10" when I can click on any link.
可能是因为警报功能的参数只有在函数调用时才被绑定?因为在循环结束后,我的最终值为10。
Could it be because the parameters to the alert function get binded only when the function is called ? Because ultimately the value of i is 10 after the end of loop.
推荐答案
简单的回答,使用 closure :
link.onclick = (function(j) {
return function(){
alert ("This is the link " + j);
return false;
}
})(i);
这篇关于一个循环中的Javascript绑定点击手柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!