Javascript 单击时更改背景

Javascript 单击时更改背景,javascript,jquery,html,css,Javascript,Jquery,Html,Css,有人能帮助我吗?我一直在寻找和阅读,但我找不到答案。我有点不喜欢jquery,所以我需要帮助。 我有一个下拉菜单。我想从中实现的是,当我单击带有sub sub下拉菜单的子菜单时,它会更改背景。现在它工作了,背景改变了,但是它应用于它的兄弟元素,它也有一个下拉列表。我想更改被单击元素的背景 jquery: $('.withsub a').on('click', function () { if ($(this).siblings('.tmenu-subs02').is(':visi

有人能帮助我吗?我一直在寻找和阅读,但我找不到答案。我有点不喜欢jquery,所以我需要帮助。 我有一个下拉菜单。我想从中实现的是,当我单击带有sub sub下拉菜单的子菜单时,它会更改背景。现在它工作了,背景改变了,但是它应用于它的兄弟元素,它也有一个下拉列表。我想更改被单击元素的背景

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');
    }
});
请参见

我更新了您的:


您正在使用Sub元素瞄准所有
。而只需要使用Sub
父元素瞄准最近的

您需要使用:

$('.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');
    }
});

$('.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');
        }
    });
您还可以使用
.toggle()
.toggleClass()


您可以执行以下操作。使用

$('.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');
        }
    });

查一查

@Sharon:很高兴这有帮助。使用toggle和toggleclass选择第二个解决方案。
$('.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');
        }
    });