On May 26, 8:57 am, SM <servandomont...@gmail.com> wrote:
> Hello,
> I have two functions: show_thumbnail() and show_photo(). See code
> below.
>
> In show_thumbnail() i create a <ul> list using Javascript and the DOM.
> In the tag <a> i create a onclick function and im passing two
> parameters to the show_photo() function, the path of the image and the
> description
>
> In show_photo(), the parameters are always the last image and
> description of the array.
> How come?
Because the anonymous functions that you assign all have closures back
to the same instaces of path and description.
> Thanks
> Marco
>
> function show_thumbnail(thumbnail)
> {
> ...
> var path, description;
> var li, a, img;
>
> var ul = document.createElement('ul');
> ul.className = 'photoThumbnail';
>
> for(var i=0; i<thumbnail.length; i++)
> {
> path = thumbnail[i].path;
> description = thumbnail[i].description;
>
> li = document.createElement('li');
>
> a = document.createElement('a');
> a.onclick = function() { show_photo(path, description); } ??????
There are a few solutions, here's two:
a.onclick = new Function(
'show_photo(' + path + ',' + description + ')'
)
or
a.onclick = (function(p, d) {
return function(){ show_photo(p, d) }
})(path, description);
or you could pass path and description to some other function that
returns the new function. There is a good post here from Mike Winter:
<URL:
http://groups.google.com.au/group/co...9e4b4d3d8d3144
>
--
Rob