$link
is out of scope for the annoynmous function inside your handler. You need to use $(this)
inside the click handler instead:
$links.each( function(i) {
$link = $(this);
$link.click( function(e) {
e.preventDefault();
console.log('L' + i + ': ' + $(this).parent().hasClass('active'));
});
});
See the updated jsFiddle.
You can also use event data to act as closures if you have to solve this without using $(this)
, for example:
$links.each( function(i) {
$link = $(this);
$link.click({ link : $link }, function(e) {
e.preventDefault();
//console.log('L' + i + ': ' + $(this).parent().hasClass('active'));
e.data.link.parent();
});
});