open closest ul on click jQuery

梦想与她 提交于 2021-01-29 02:45:27

问题


when clicking a.market-metro, open closest ul.children.

<ul class="drop-padding">
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>

I have the following but not working:

jQuery(".market-metro").click(function(){
    if (jQuery(".market-metro").closest('li').find('ul.children').hasClass("expanded")) {
        jQuery(".market-metro").closest('li').find('ul.children').removeClass("expanded").slideUp(250);
    } else {
        jQuery(".market-metro").closest('li').find('ul.children').addClass("expanded").slideDown(250);
    }
});

回答1:


you need to use $(this) .. and you can use .next() instead of closest and find and use .not()

$(".market-metro").click(function(){
    $('ul.children').not( $(this).next('ul.children')).removeClass("expanded").slideUp();
    $(this).next('ul.children').toggleClass("expanded").slideToggle(250);
});

Working Demo

Note: be sure to include jquery



来源:https://stackoverflow.com/questions/34190258/open-closest-ul-on-click-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!