I have created a Javascript toggle menu:

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.toggle').next().slideUp("fast").removeClass("expanded");
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

When I click on another item in the menu, the class "expanded" is not removed from the other elements. I've tried many different things but can't get my head around it. Any help would be appreciated.

有帮助吗?

解决方案

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");
            $(this).addClass('collapsed');
            $(this).removeClass('expanded');
        } else {
            var $expandedItems = $('.expanded');
            $expandedItems.next().slideUp("fast")
            $expandedItems.addClass('collapsed');
            $expandedItems.removeClass('expanded');
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

Based on your comments I think you are after something like this.

其他提示

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.expanded').removeClass('expanded');//here is your problem
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

This should be remove expanded class from your jquery code

Note Tested although please tell me if its not working

updated

Demo

And for jquery i think you are missing too much information here check demo here Demo

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top