0

I'm trying to assign a click function to a list of links. I want the function for each element to be unique. Using a for loop I incriment on i, and use that in the function.

The result however, has every element using the last version of 'i'

Here's the code.

(function(){
    var d = dash_bar_rev_by_commodity;
    var vals = d.data()[0].values;
    var list = $('ul.hidden-links');
    for (var i=0;i<vals.length;i++)
    {
        list.append('<li><a href="#">Filter by '+vals[i].x+'</a></li>')
        $('ul.hidden-links li:last-child a').click(function(){
            $('.bar:eq('+i+')')[0].__onclick();
        });
    }
})();
rbristow
  • 183
  • 2
  • 15
  • 2
    You can find information about the problem here: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/218196). However, there are probably better solutions in your case. – Felix Kling Sep 12 '14 at 15:37
  • Felix Kling, thank you, thats what i was looking for. Didn't know how to search for it. – rbristow Sep 12 '14 at 15:43

0 Answers0