开发者

jQuery: Adding class to the li element after the link is clicked, and deselecting all other classes

I am generating menu with such tags:

<div class="animatedtabs">
  <ul>
    {% for item in menu_items %}
    <li><a href="{{ item.url }}" title="{{ item.name }}"><span>{{ item.name }}</span></a></li>
 开发者_运维百科   {% endfor %}
  </ul>
</div>

What I want to do, I want to add class="selected" to li, after the link is clicked, and to remove all other class="selected" on other li's...

Also I wonder, how to show menu in the way, so the first item is selected by default... But then when another linked is clicked, then class="selected" is toggled


    $(function() {


    $('.animatedtabs ul a').click(function() {

         $('.animatedtabs ul a').removeClass('selected');
         $(this).addClass('selected');

        return false;
    }).filter(':first').click();
});

this make all you have asked real! ;-)


There is a related question about navigation menus in Django: Navigation in django

This answer has a good example of using a template tag for adding the classes to the li elements. Navigation in django


Like this:

$('.animatedtabs li a').click(function() {
    $('.animatedtabs li').removeClass('selected');
    $(this).closest('li').addClass('selected');
    //Do something
    return false;
});


Just remove "selected" from the class string of all the <li> elements, and then add it to the one that's been clicked.

$('li.foo').click(function(li) {
  $('li').removeClass('selected');
  $(this).addClass('selected');
});


I would say that an even more elegant method is as follows:

$(function() {

    // Make the first list item selected
    $('.animatedtabs li:first').addClass('selected');

    // The first item is automatically deselected when another is clicked
    $('.animatedtabs li').click() {

        // Make the current li selected
        $(this).addClass('selected');

        // Remove the selected class from any currently selected sibling items
        $(this).siblings('.selected').removeClass('selected');

        return false;
    }

});

I have used this method whilst recently creating a direct copy of the Mac OS finder window using just jQuery HTML and CSS for a project I am working on, and it works magically there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜