I have a jQuery plugin that adds a series of links to my page, and when each one is clicked, it should display the index of the link. The problem is that every link displays the string "11". This is because when I bind the click method, I pass in an actual function, which doesn't get interpreted until its called. So its always holding a reference to the variable i, and hence, uses its current value, which ends up being 11.
The reason I can't simply do: $link.bind('click', 'alert(' + i + ');'); is because I need the click event to call a function WITHIN the plugin. Is there a correct way to do this? I need to call a function within the plugin and pass in the i index variable. jQuery.fn.myplugin = function() { return this.each(function() { function alertme(str) { alert (str); } for (int i = 0; i < 10; i++) { var $link = jQuery('<a></a>'); $link.html(i); $link.bind('click', function() { alertme(i); }); $this.append(link); } } };