views:

22

answers:

1

I am trying to run the following code:

I pass parameter to a function, but it always has the value of the last object run through the loop. I read some articles about it on stackoverflow, but I couldn't find out how to make it run in my solution.

The object is a JSON object returned from the server. All it's values are correct.

for(var i = 0;i<parents.length;i++){
            var row        = $(document.createElement("tr"));
            var colName    = $(document.createElement("td"));

            var aDisplayCol = $(document.createElement("a"));

            var parentId = parents[i]['PARENT_ID'];

            aDisplayCol.attr("href","#").html(parents[i]['NAME']);
            aDisplayCol.bind('click',function(){ alert(parentId);});


            colName.append(aDisplayCol);

            row.append(colName);
            $('#pages tbody').append(row);                

}

Thanks

+1  A: 

Perhaps there's a problem with using parentId in the callback.

Try alert(parents[i]['PARENT_ID']);.

EDIT: Let's see if we can get around our scope issues with .data().

aDisplayCol.data("parentId",parents[i]['PARENT_ID']);
aDisplayCol.click(function() {
   alert($(this).data('parentId'));
});
DLH
Nope, that's not causing it. Actually, I discovered yesterday that the .click function can't handle the following: aDisplayCol.click(function(){ whatever(target,dest, parents[i]['PARENT_ID']); return false; });I assume it is a bug. Passing a variable instead works fine.
Kel
Nah I don't think it's a bug. I think it's a scope issue. I don't think `i` exists within the scope of the click handler.
DLH
you forgot to close the parenthesis at .data
Kel
Yep I noticed. Fixed! Does this work?
DLH
using .data worked! AWESOME :D thanks. It is a closure problem.
Kel