简体   繁体   English

jQuery问题-具有相同类的不同菜单之间的冲突

[英]jQuery Problem - Conflict between different menu with same class

Hi all i am still learning jQuery and i am having a problem with my menu. 大家好,我仍然在学习jQuery,我的菜单有问题。 When i click on any menu with class "tm-nav-vertical" or "tm-nav-horizontal" it removes .active class in the first menu. 当我单击具有“ tm-nav-vertical”或“ tm-nav-horizo​​ntal”类的任何菜单时,它将在第一个菜单中删除.active类。 I don't want to create a code that is for specific menu cause i want to re-use it always (example .menu1 .menu2). 我不想为特定菜单创建代码,因为我想一直重复使用它(例如.menu1 .menu2)。

I was trying to use something like .siblings but i didn't manage to make it work. 我试图使用.siblings之类的东西,但没有设法使其正常工作。

$(function () {
$('.tm-nav-vertical ul li, .tm-nav-horizontal ul li').click(function () {
    if ($(this).hasClass("tm-dropdown-button")) {
        if ($(this).hasClass("active")) {
            $(this).removeClass('active');
        } else {
            $('.tm-nav-vertical > ul li.active, .tm-nav-horizontal > ul li.active, .tm-dropdown-button').removeClass('active');
            $(this).addClass('active');
        }
    } else {
        $('.tm-nav-vertical ul li.active, .tm-nav-horizontal ul li.active').removeClass('active');
        $(this).addClass('active');
    }
});});

Using calls like: 使用如下调用:

$('.tm-nav-vertical ul li.active, .tm-nav-horizontal ul li.active')

are going to select elements from anywhere in the document. 将要从文档中的任何位置选择元素。

What you want to do is find the parent menu first then find the element(s) you want to modify. 您要执行的操作是先找到父菜单,然后找到要修改的元素。 You can get the parent menu by calling jQuery's (or even DOM api's ) closest() method passing in the class selector of the menu. 您可以通过调用菜单的类选择器中的jQuery(甚至是DOM api的closest()方法来获取父菜单。 It will find the closest ancestor element that matches the passed selector. 它将找到与传递的选择器匹配的最接近的祖先元素。

var parentMenu = $(this).closest('.tm-nav-vertical, .tm-nav-horizontal');
parentMenu.find('ul li.active').removeClass('active');

Note if your menu is more complex (multiple levels, multiple ".active" elements, etc) you will have to do something more than a simple find() 请注意,如果您的菜单更复杂(多个级别,多个“ .active”元素等),则除了简单的find()之外,您还需要做更多的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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