通过循环传递事件侦听器上的参数 [英] Passing parameters on event listeners with loops

查看:93
本文介绍了通过循环传递事件侦听器上的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需一个简单的问题,任何人都可以告诉我为什么这不工作,如何解决?本质上,它采用HTML中的一组表格行,并将点击事件动态附加到它们。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆