Jquery toggleclass

时间:2012-09-27 10:19:33

标签: css jquery-ui accordion addclass

我有一个手风琴菜单,使用下面的脚本

开发
$(document).ready(function(){

    $('li.button a').click(function(e){
     $(this).addClass('active');

        /* Finding the drop down list that corresponds to the current section: */
        var dropDown = $(this).parent().next();

        /* Closing all other drop down sections, except the current one */
        $('.dropdown').not(dropDown).slideUp('100');
        dropDown.slideToggle('100');

        /* Preventing the default event (which would be to navigate the browser to the link's address) */
        e.preventDefault();     })      

});

我需要在单击菜单时添加.active类,所以我在jquery中添加了addclass,它正在添加类,但问题是当单击另一个菜单时应该删除该类。我甚至试过toggleclass但是没有用。

此外,我希望在打开页面时默认打开第一个li项目。

3 个答案:

答案 0 :(得分:0)

只需在功能开头添加:

$('li.button a').click(function(e){
    $('li.button a').removeClass('active');
    $(this).addClass('active');
    ...
});

答案 1 :(得分:0)

试试这个

$('li.button a').each(function(){
    $(this).removeClass("active").addClass("no-active"); // your non active class
});

答案 2 :(得分:0)

$('li.button a').click(function(e){
     if($(this).hasClass('active')) // this line verifies if the actual clicked element is already active
         return false;  // you can return false or do another operation here

     $('li.button a.active').removeClass('active');

     $(this).addClass('active');

     /* Finding the drop down list that corresponds to the current section: */ 
        var dropDown = $(this).parent().next(); 

        /* Closing all other drop down sections, except the current one */ 
        $('.dropdown').not(dropDown).slideUp('100'); 
        dropDown.slideToggle('100'); 

        /* Preventing the default event (which would be to navigate the browser to the link's address) */ 
        e.preventDefault();     
})