Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if an开发者_JAVA技巧yone knows a better way to write it. Thanks!
$('.nav li a').eq(0).click(function() {
$('.nav li a').eq(0).addClass("active");
$('.nav li a').eq(1).removeClass("active");
$('.nav li a').eq(2).removeClass("active");
$('.nav li a').eq(3).removeClass("active");
});
$('.nav li a').eq(1).click(function() {
$('.nav li a').eq(0).removeClass("active");
$('.nav li a').eq(1).addClass("active");
$('.nav li a').eq(2).removeClass("active");
$('.nav li a').eq(3).removeClass("active");
});
$('.nav li a').eq(2).click(function() {
$('.nav li a').eq(0).removeClass("active");
$('.nav li a').eq(1).removeClass("active");
$('.nav li a').eq(2).addClass("active");
$('.nav li a').eq(3).removeClass("active");
});
$('.nav li a').eq(3).click(function() {
$('.nav li a').eq(0).removeClass("active");
$('.nav li a').eq(1).removeClass("active");
$('.nav li a').eq(2).removeClass("active");
$('.nav li a').eq(3).addClass("active");
});
I'd move the class to the <li>
, like this:
$('.nav li').click(function() {
$(this).addClass("active").siblings().removeClass("active");
});
If you just changing the styling to match, for example:
li.active a { /* styles */ }
...then it's much simpler overall to have the click
handler on the <li>
elements, since those are the set you're dealing with. There's also the more efficient .delegate()
method:
$('.nav').delegate('li', 'click', function() {
$(this).addClass("active").siblings().removeClass("active");
});
You have a lot of code which can be condensed. Try this:
$('.nav li a').click(function()
{
$('.nav li a').removeClass('active');
$(this).addClass('active');
});
$('.nav li a').bind('click', function() {
$('.nav li a').removeClass('active');
$(this).addClass('active')
});
$('.nav li a').click(function() {
$('.nav li a.active').removeClass("active");
$(this).addClass("active");
});
$('.nav li a').click(function() {
$('.nav li a').removeClass('active');
$(this).addClass('active');
});
Removes the active
class from each a and then adds it to the clicked element.
I'm making some assumptions about what your document looks like, but this is what I might do:
$('.nav li a').click(function() {
$('.nav li a').removeClass('active');
$(this).addClass('active');
});
精彩评论