简体   繁体   English

使用闭包遍历具有变量的jQuery选择器

[英]Iterating over jQuery selector with variable, using closures

[First time on stackoverflow.] I am trying to dynamically add html buttons to my page and then give them a javascript function to run when they are clicked, using jQuery's click. [第一次使用stackoverflow。]我试图将html按钮动态添加到我的页面,然后为它们提供一个javascript函数,以使用jQuery的单击在单击它们时运行。 I want to have one button for each element in an array, so I used a for loop. 我想为数组中的每个元素设置一个按钮,所以我使用了for循环。 My code looks like this (simplified) 我的代码看起来像这样(简化)

for (var i = 0; i < results.length; i++) {
    $("#" + place[i].place_id).click(function(){console.log("Test");})        
    $("#" + place[i].place_id).click();
}

(I inject buttons with the right id's in the same loop.) This code, when run, console logs "Test" the right number of times, but afterwards, only the last button responds "Test" when clicked. (我在同一循环中注入了具有正确ID的按钮。)运行此代码时,控制台将“ Test”记录正确的次数,但是此后,只有最后一个按钮在单击时才响应“ Test”。 (This situation is a little absurd.) So, I think the event handler ends up using only the final value of i to assign the event handler. (这种情况有点荒谬。)因此,我认为事件处理程序最终仅使用i的最终值来分配事件处理程序。 I think the problem has to do with closures, but I am not sure how to make a closure out of a jQuery Selector (and in general am not familiar with them). 我认为问题与闭包有关,但我不确定如何从jQuery选择器中进行闭包(通常对它们不熟悉)。

In contrast, as a hack solution, I "manually" wrote code like the below right below and outside the for loop, and it works as expected, in that clicking causes the console log. 相反,作为一种hack解决方案,我“手动”在for循环的下方和下方编写了以下代码,并且按预期方式工作,因为单击会导致控制台日志。

$("#" + place[0].place_id).click(function(){console.log("Test"););
$("#" + place[1].place_id).click(function(){console.log("Test");});
etc.

(Of course, this all occurs within a larger context - specifically a Google Maps Places API call's callback.) (当然,所有这些操作都在较大的上下文中发生-特别是Google Maps Places API调用的回调。)

First, am I understanding the problem correctly? 首先,我是否正确理解问题? Second, what would work? 第二,什么可行? Should I take a different approach altogether, like use a .each()? 我是否应该完全采用其他方法,例如使用.each()?

(I later would want to display a property of place[i] when clicked, which I would think would need another callback My final hack code looks like this: (我以后想在单击时显示place [i]的属性,我认为这需要另一个回调。我的最终hack代码如下所示:

$("#" + place[0].place_id).click(function(){google.maps.event.trigger(placeMarkers[0], "click"); repeated 20 times

To do this, you can simply create a self executing function inside the for loop, like this: 为此,您可以在for循环内简单地创建一个自执行函数,如下所示:

for (var i = 0; i < results.length; i++) {
    (function(index) {
        $("#" + place[index].place_id).click(function() { 
            //Do something with place[index] here 
        });
    })(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM