简体   繁体   中英

Change background when clicked

Can somebody help or assist me ?I have been searching and reading but I am nowhere to find answers. I am kinda not into jquery so I need help. I have a drop down menu. What I would like to achieve from that is , when I click the sub menu with sub sub drop down menu it changes background. Now it worked, the background changes, but it applies to its sibling elements which has also a drop down. I would like to change the background of the element which is clicked.

The jquery:

    $('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $('.withsub').removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $('.withsub').addClass('clicked');
    }
});

please see actual demo

I updated your fiddle :

$('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $(this).parent().removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $(this).parent().addClass('clicked');
    }
});

You are targetting all .withsub elements whereas you need to only target closest .withsub parent element.

You need to use:

$('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $(this).closest('.withsub').removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $(this).closest('.withsub').addClass('clicked');
    }
});

Working Demo

You can also narrow down your code by using .toggle() and .toggleClass()

$('.withsub a').on('click', function () {
        $(this).siblings().toggle();
        $(this).closest('.withsub').toggleClass('clicked');
});

Demo using toggle and toggleclass

You can do like following. Use .children()

$('.withsub').on('click', function () {
        if ($(this).children('.tmenu-subs02').is(':visible')) {
            $(this).children('.tmenu-subs02').hide();
            $(this).removeClass('clicked');
        } else {
            $(this).children('.tmenu-subs02').show();
            $(this).addClass('clicked');
        }
    });

Check Updated Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM