开发者

jQuery add + remove classes to/from multiple elements

I've been searching and can't quite figure out how to shorten this code I've made for this site's navigation. I'm afraid I'm new to Javascript and jQuery. Thanks in advance.

The page never reloads, so I've done the following to display what page is currently being viewed:

The menu:

<ul>
  <li><a href="#" class="nav on" id="navitem1" onclick="showMiddle(1);">item 1</a></li>
  <li><a href="#" class="nav" id="navitem2" onclick="showMiddle(2);">item 2</a></li>
  <li><a href="#" class="nav" id="navitem3" onclick="showMiddle(3);">item 3</a></li>
  <li><a href="#" class="nav" id="navitem4" onclick="showMiddle(4);">item 4</a></li>
  <li><a href="#" class="nav" id="navitem5" onclick="showPhotos(5);">item开发者_C百科 5</a></li>
</ul>

The rest:

function changeClass1() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem1").addClass('on');
    }
};
function changeClass2() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem2").addClass('on');
    }
};
function changeClass3() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem3").addClass('on');
    }
};
function changeClass4() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem4").addClass('on');
    }
};
function changeClass5() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem5").addClass('on');
    }
};
function changeClass6() 
{
    if ($(".nav").hasClass('on'))
    {
        $('.nav').removeClass('on');
        $("#navitem6").addClass('on');
    }
};

$("#navitem1").click(changeClass1);
$("#navitem2").click(changeClass2);
$("#navitem3").click(changeClass3);
$("#navitem4").click(changeClass4);
$("#navitem5").click(changeClass5);
$("#navitem6").click(changeClass6);


$(".nav").on("click", function () {
    $(".nav").removeClass("on");
    $(this).addClass("on");
});

That says: when any .nav is clicked, first remove all .on's from all .nav's, then add it back to the element that was clicked.

Note that you don't need to check if something has a class before removing it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜