I'm going to go out on a limb here and suggest that instead of continuously writing code that works around your markup, structure your markup so that your code works automagically.
You should mark all your nav links with a common class instead of an ID:
<a href="#" class="navlink">Link 1</a>
<a href="#" class="navlink">Link 2</a>
<a href="#" class="navlink">Link 3</a>
and all your hidden divs in a similar manner:
<div class="navhidden">foo</div>
<div class="navhidden">bar</div>
<div class="navhidden">herp</div>
Now your code can just be something as simple as:
jQuery(function($) {
var $navlinks = $('.navlink'),
$navhiddens = $('.navhidden'),
$overlay = $('#overlay');
$navlinks.on('click', function (e) {
// this is your link
$link = $(this);
// get my hidden div + toggle
$my_navhidden = $navhiddens
.eq($navlinks.index(this))
.toggle();
// hide all the other navhiddens
$navhiddens.not($my_navhidden).hide();
// hide or show the overlay?
if ($navhiddens.filter(':visible').length > 0) {
$overlay.show();
} else {
$overlay.hide();
}
});
});
This has the advantage of being able to add more links + navhiddens on your markup without changing a single thing in your code. Additionally, how easy is it to add something like .navhidden { display:none; }
in your CSS to hide everything?
Instead of changing $('#nav1,#nav2,#nav3')
to $('#nav1,#nav2,#nav3,#nav4')
and so on and so forth when you add a new link, use the time to get yourself a cup of coffee instead. You can use Javascript / jQuery to determine the ordinal index of an element anyway; there's virtually no need to mark your DOM elements with ordinal sequences like nav1
nav2
nav3
... navn
.
As a side note, the .on
syntax is jQuery 1.7.x. If you're not using that, change that to .bind
.
EDIT
Added in a bit of code to logically toggle the overlay on and off. It's not the most elegant, but you get the gist.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…