开发者

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. 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.开发者_StackOverflowlength; 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.

Thanks in advance for any help.

Mister 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.

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.


Ah, this is a classic closure issue.

You'll need to pass in the object.id to a wrapper function, like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜