简体   繁体   English

动态列表中的匿名函数传递相同的参数值

[英]Anonymous function in dynamic list being passed same parameter value

I'm building a <ul> dynamically within an object array where each list item calls a function when a link is clicked. 我正在一个对象数组中动态构建一个<ul> ,其中每个列表项在单击一个链接时调用一个函数。 However, the function is only ever being passed the parameter from the last item in the object array. 但是,该函数仅从对象数组中的最后一项传递参数。 Here is my code... 这是我的代码......

var list = document.createElement("ul");
var object;

for (var i = 0; i < myObjects.length; i++)
{
    object = myObjects[i];

    listItem = document.createElement("li");
    image = document.createElement("img");
    image.setAttribute("src", object.image_url)
    listItem.appendChild(image);
    listItem.appendChild(document.createTextNode(object.title));

    link.setAttribute("href", "#");
    link.addEventListener("click", function(){someFunction(object.id);}, false);
    link.appendChild(document.createTextNode("Click Me!"));
    listItem.appendChild(link);

    list.appendChild(listItem);
}

element.appendChild(list);

All the variables are declared within this same function, so no globals are used. 所有变量都在同一个函数中声明,因此不使用全局变量。 Before anyone suggests it, I'm not using jQuery because I'm trying to get my head round the basics of javascript before I move on to using any libraries. 在有人提出建议之前,我并没有使用jQuery,因为在我继续使用任何库之前,我正试图了解javascript的基础知识。

Thanks in advance for any help. 在此先感谢您的帮助。

Mister B. 先生B.

Due to the way scope works, the anonymous function has a reference to the variable , not to its value . 由于范围的工作方式,匿名函数具有对变量的引用,而不是其 When you change that variable later, the change is reflected in the anon function. 稍后更改该变量时,更改将反映在anon函数中。

Perhaps using a closure trick could work? 也许使用封闭技巧可行吗?

Change 更改

link.addEventListener("click", function(){someFunction(object.id);}, false);

To

(function(O) {
   link.addEventListener("click", function(){someFunction(O.id);}, false);
})(object);

If I'm not mistaken, that oughta create a new variable, whose value will be unaffected by subsequent changes to object in the for loop. 如果我没有弄错的话,那就是创建一个新的变量,它的值不会受到for循环中object的后续更改的影响。

Ah, this is a classic closure issue. 啊,这是一个典型的关闭问题。

You'll need to pass in the object.id to a wrapper function, like this: 您需要将object.id传递给包装函数,如下所示:

(function(id) {
   link.addEventListener("click", function(){someFunction(id);}, false);
})(object.id);

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

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