Toggle/Show one defined DIV with JS

2019-07-20 05:11发布

问题:

I have a fiddle for you: http://jsfiddle.net/vSs4f/

I want to show the div.sub-menu with a simple click on a.haschildren. If the body loads the div.sub-menu should be closed. If I click a second time on a.haschildren the div.sub-menu should be close.

I have sampled so many things but I think the problems are the lot of DIV's. One idea is in the fiddle.

$(function()   {
    $("a.haschildren").click(function(e) {
        e.preventDefault();
        $('div.sub-menu:visible').hide();
        $(this).next('div.sub-menu').show();
    });
});

I really hope you can help me, thanks!

回答1:

Try

$(function()   {
    $("a.haschildren").click(function(e) {

        e.preventDefault();
        var item = $(this).closest('div.haschildren').next().next('div.sub-menu').toggle();
        $('div.sub-menu:visible').not(item).hide();
    });
});

Demo: Fiddle



回答2:

Try this:-

Fiddle

 $(function () {
    $("a.haschildren").click(function (e) {
        e.preventDefault();
        var subMenu = $(this).closest('div.haschildren').nextUntil('.sub-menu').next().toggle();
        $('div.sub-menu:visible').not(subMenu).hide();

    });
});

Using .nextUntil to reach a point till the .sub-menu, incase any other siblings come in between this will still work.



回答3:

Personally there are MANY things I would have changed about the structure of your DOM. I am a strong believer that you should base your javascript structure around a well structured DOM, so the traversal is very easy and intuitive. That being said, I'm going to be slightly daring by submitting my fiddle, in the hope that if nothing else, you can look at it and gain a little insight on how to take advantage of a few DOM quirks to make your javascript a bit more intuitive and elegant.

http://jsfiddle.net/vSs4f/6/

$(function()   {
    $('#menu > div.item')
        .find('a').click(function() {
            var submenu_index = $(this).parents('.item:first').find('.sub-menu').toggle().index('.sub-menu');

            // This chunk can disappear if you're not interested in hiding all of the other sub-menus
            $('.sub-menu').filter(function(index) {
                if(index != submenu_index)
                    return true;
            }).hide();
        }).end()
        .find('div:first').after('<div class="trenner"></div>');
});


回答4:

just use toggle()

$('div.sub-menu').toggle();


回答5:

Ironically enough, the method you're looking for is .toggle();

http://api.jquery.com/toggle/



回答6:

try it:

$(function()   {
    $("div.haschildren").click(function() {
        if($(this).next().next('div.sub-menu').is(":hidden")){
            $('div.sub-menu:visible').hide();
            $(this).next().next('div.sub-menu').show();
        }else{
            $(this).next().next('div.sub-menu').hide();
        }
        return false;
    });
});