[英]Passing loop variable as argument in element function
Forgive the title, wasn't sure what to put. 原谅标题,不确定要放什么。
I have some code like: 我有一些类似的代码:
var links=document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
var cur=links[i];
cur.onmouseover=function(){alert(i);};
}
I remember seeing something like this before, but I have no clue how I would go about finding it. 我记得以前曾经见过类似的东西,但是我不知道如何去寻找它。 If another question like this has been asked, I would be far from surprised and would appreciate the link. 如果有人问过类似这样的问题,我不会感到惊讶,并且希望知道该链接。
edit: the problem is that it always alerts what 'i' is after the loop finishes. 编辑:问题是循环结束后,它始终会警告“ i”是什么。 If there are two links, they all alert 2. 如果有两个链接,它们都将发出警报2。
edit: I remembered seeing it here: http://nathansjslessons.appspot.com/ . 编辑:我记得在这里看到它: http : //nathansjslessons.appspot.com/ 。 Great few lessons, I suggest anyone who hasn't already to do them. 很棒的几课,我建议任何尚未做过的人。
Try this: 尝试这个:
var links=document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
var cur=links[i];
cur.onmouseover=function(a){
return function(){
alert(a);
}
}(i);
}
You can actually use Array.forEach
: 您实际上可以使用Array.forEach
:
var links=document.getElementsByTagName('a');
[].forEach.call(links, function(cur, i) {
cur.onmouseover = function() { alert(i); };
})
The trick is using .call()
, passing links
as the this
parameter. 诀窍是使用.call()
,并将links
作为this
参数传递。
You'll need to add .forEach()
for older browsers that don't support it natively. 您需要为本身不支持它的旧版浏览器添加.forEach()
。
This is a more reusable solution. 这是一个更可重用的解决方案。 remember the 3 r's reduce reuse recycle ;) it overflows into real life. 记住3 r的减少重复使用回收;)它溢出到现实生活中。 see which is quickest optimization fun! 看看哪个是最快的优化乐趣! http://jsperf.com/speed-test-for-links-script http://jsperf.com/speed-test-for-links-script
var links = document.getElementsByTagName('a');
var linksLength = document.getElementsByTagName('a').length //cache the length means quicker for loop
var addMouseOver = function(i){
links[i].onmouseover=function(){
alert(i);
};
} //extract the function
for(var i=0;i<linksLength;i++){
addMouseOver(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.