通过循环传递事件侦听器上的参数 [英] Passing parameters on event listeners with loops
问题描述
for(var a = index; a< ; rows.length; a ++){
tr = rows [a];
tr.onclick = function(){DropDownManager.onItemClick(tr,a); };
tr.observe(click,function(){DropDownManager.onItemClick(tr,a);});
}
此代码的问题是传递给DropDownManager.onItemClick的值总是循环中的最后一个项目,这不是im后,因为我希望他们成为循环的那个阶段的当前值。我意识到我错过了一些非常简单的东西,但是我的生活中却无法实现。
JavaScript没有阻止范围,所以例如循环不会创建一个新的范围。您可以使用以下函数创建一个:
for(var a = index; a< rows.length; a ++){
(function(a){
tr = rows [a];
tr.onclick = function(){DropDownManager.onItemClick(this,a);};
tr.observe (click,function(){DropDownManager.onItemClick(this,a);});
}(a));
}
根据行
和 tr
,你甚至可能不需要循环索引。也许您可以通过另一种方式获取事件处理程序中的元素索引。例如。如果 tr
是 HTMLTableRowElement
[MDN] ,那么您可以通过获得其他行中的位置。 rowIndex
。
Btw。你为什么绑定相同的事件处理程序两次?
Just a quick question, can anyone tell me why this doesnt work and how to fix it? Essentially its taking a group of table rows in HTML and dynamically attaching click events to them.
for (var a=index; a<rows.length; a++) {
tr = rows[a];
tr.onclick = function() { DropDownManager.onItemClick(tr, a); };
tr.observe("click", function() { DropDownManager.onItemClick(tr, a); });
}
The problem with this code is that the values passed into DropDownManager.onItemClick are always the last items in the loop, this isn't what im after as i wanted them to be the current value in that stage of the loop. I realize I'm missing something quite simple but cant for the life of me work it out!
JavaScript has no block scope, so e.g. loops don't create a new scope. You can create one by using a function:
for (var a=index; a<rows.length; a++) {
(function(a) {
tr = rows[a];
tr.onclick = function() { DropDownManager.onItemClick(this, a); };
tr.observe("click", function() { DropDownManager.onItemClick(this, a); });
}(a));
}
Depending on what rows
and tr
are, you might not even need the loop index. Maybe you can get the elements index inside the event handler through another way. E.g. if tr
is a HTMLTableRowElement
[MDN], then you can get its position among the other rows via this.rowIndex
.
Btw. why are you binding the same event handler twice?
这篇关于通过循环传递事件侦听器上的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!