【问题标题】:jQuery attach event handler in each loop [duplicate]每个循环中的jQuery附加事件处理程序[重复]
【发布时间】:2012-07-16 09:55:14
【问题描述】:

我有一个这样的选项对象:

//buttons = html-button elements with id's
buttonTypes: {
"open" : ['#button1', '#button2'], 
"close" : ['#button3', '#button4'] 
} 

现在我想为每个buttonTypes.key 中的元素分配点击处理程序。 与“打开”相关的按钮应调用同名函数 和“close”相关的应该调用一个叫做close的函数 所以我写了这个循环:

for(a in buttonTypes) {
    $(buttonTypes[a]).each(function(i,button){ 
        $(button).click(function(e) {
            that[a]();
        });
    });
}

问题:

当我点击按钮时,调用的唯一函数是close() - 所以它似乎总是最后一个。我做错了什么?

【问题讨论】:

  • 我(就像我 8 年前问过这个问题一样)不同意链接帖子中已经给出了答案,而这个答案在当时是重复的。这个问题与范围无关,代码是 jQuery 而不是 vanilla JS。

标签: jquery event-handling javascript-objects each jquery-events


【解决方案1】:

因为that[a](); 在您单击按钮之前不会被评估;到那时,它是close

您应该做的是创建a 的本地副本;

for (a in buttonTypes) {
    $(buttonTypes[a]).each(function(i,button){
        var type = a;

        $(button).click(function(e) {
            that[type]();
        });
    });
}

别忘了var a (for (var a in buttonTypes))。

【讨论】:

  • 耶,是吗 :-) 你是对的,谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 2012-05-10
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多