You'd need to pass the reference to i as a parameter to the inner function such that the i is now local to the function. It appears that you're binding multiple events based on a click to the outer divs which is then binding multiple click events to the div's inner anchor tag to hide all divs which aren't a parent of the anchor tag.
Here is my solution:
HTML
<div id="wrapper">
<div class='container container1'>
<div class='content'>
<h1><a href='#'>Title</a></h1>
<p>Content</p>
</div>
</div>
<div class='container container2'>
<div class='content'>
<h1><a href='#'>Title</a></h1>
<p>Content</p>
</div>
</div>
<div class='container container3'>
<div class='content'>
<h1><a href='#'>Title</a></h1>
<p>Content</p>
</div>
</div>
</div>
JavaScript
var $context = $('#wrapper'),
$containers = $('#wrapper').find('div.container');
$context.on('click', '.container a', function() {
var $theAnchorClicked = $(this),
parentClassofAnchor = $this.parent().parent().parent().prop('class');
$containers.each(function() {
$theCurrentContainer = $(this);
if (!$(this).hasClass(parentClass)) $(this).hide();
});
});
First, I wrapped the all 'container' divs in a wrapper div ('#wrapper') which is used as a context for finding the containers. This is simply because finding an element by an id, tag, or within a context is much faster than finding by class name. Always.
I saved a reference to the wrapper ($context) and then from $context found all the divs with the class 'container' and also saved a reference to that.
Second, instead of binding a click function to each link, I'm delegating a click event to the $context when a link inside the context is clicked (1 event bound instead of 20). I'm also using jQuery's .on() method as it is recommended for jQuery 1.7+.
So what's going on in the click event being delegated to $context? The .on() method is specifying a 'click' event on an element matching '.container a' and then the function to perform. In the function, this is a reference to the link being clicked.
The link being clicked is saved, as well as the class(es) of the parent div.container, e.g. '.container .container1'. You'll notice there are several parents being traversed to find it since the link is nested in several other elements.
Now that these are saved, I'm using jQuery's .each() method to traverse through all the containers we saved in $containers. We need to check for all the containers that don't have the class we found (parentClassofAnchor) and hide those. In the .each() function, this is not a reference to the link, it is now a reference to the current div.container in the loop ($theCurrentContianer). Then we use a simple if statement to check if it doesn't have the class we want to show, in which case we hide that div.
I hope this helps! Please let me know if you were looking to do more with your click events.