javascript - jQuery 单击时,切换 next() 元素,但关闭所有同级元素

标签 javascript jquery html css

我有一个功能,以便当用户单击 span.open 时,会打开带有 .footer-menu-accordion 类的下一个元素。这个切换功能效果很好。但是,如果我单击下一个 span.open (例如,我单击了 Men anchor 旁边的 span,然后单击 Women anchor 旁边的 span),则已经打开的 .footer-menu-accordion不关闭。仅当我再次单击 span.open 时它才会关闭。

我希望每次单击 span.open 时,紧随其后的 .footer-menu-accordion 都会打开,但如果有任何其他 .footer-menu-accordion div 打开,这些将关闭。我想我需要以 sibling 为目标,但我不知道如何做。这是我的 html:

    <div class="dropdown-container">
          <a class="level-1 direct">Men</a><span class="open"></span> 
    </div>

    <div class="footer-menu-accordion">
       <a class="level-2"></a>
    </div>

    <div class="dropdown-container">
          <a class="level-1 direct">Women</a><span class="open"></span> 
    </div>

    <div class="footer-menu-accordion">
       <a class="level-2"></a>
    </div>

这是我的 jQuery:

function mobileMainNav(){
    $('a.level-1.direct').click(function(){
        window.location = $(this).attr('href');
    }); 


    $('span.open').click(function(){
        $(this).toggleClass('arrow');
        $(this).parent().next('.footer-menu-accordion').slideToggle();
        if ($(this).siblings(':visible')) {
            $(this).siblings.hide();
        };
    }); 

};

谁能帮我解决这个问题吗?

最佳答案

如果我正确理解你的问题,那么应该可以通过更新你的 jQuery 脚本来实现你所需要的,如下所示:

function mobileMainNav(){
    $('a.level-1.direct').click(function(){
        window.location = $(this).attr('href');
    }); 


    $('span.open').click(function(){
        $(this).toggleClass('arrow');

        // Toggle accordion menu related to this span
        $(this).parent().next('.footer-menu-accordion').slideToggle();

        // Hide other accordion menus that are not related to this span, 
        // via slideUp()
        $('span.open')
        .not(this)
        .parent()
        .next('.footer-menu-accordion')
        .slideUp(); 

        // Remove the arrow class on other menus
        $('span.open')
        .not(this)
        .removeClass('arrow');
    }); 

};

希望有帮助!

关于javascript - jQuery 单击时,切换 next() 元素,但关闭所有同级元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980512/

相关文章:

javascript - iframe 随内容变化自动调整高度

javascript - 如何用 HTML DOM 替换替换字符串

javascript - 仅使元素符号可点击

javascript - 提交折叠 div 并更改 div 中的图像后的 Ajax 表单

javascript - 当 p 标签接近时向下移动元素

javascript - if 语句的嵌套循环问题

javascript - 将监听器附加到按钮以使用 AJAX 发送表单数据与使用标准 HTML 表单有什么区别?

javascript - Angular (2+?) 在 8 上进行测试,悬停时打开和关闭 Material 垫菜单 [解决方案]

javascript - 如何将文本文件内容保存到Javascript变量?

javascript - html 中的链接不起作用