jquery点击只影响指定的child

jquery click only affect specified child

我尝试创建一个包含多个 sub-menus 的菜单。我的想法是对每个子菜单使用 divs 高度:0px 和边框,所以它显示为一条线(仅在悬停时,模仿已知的 'this is a clickable link').如果您按下它,它会使用 jQuery 的动画展开并显示子菜单。

问题 1: jQuery 代码始终为 每个 div 设置动画 class 'submenu'。我尝试使用这样的东西只影响 children

if ($(this, '.submenu')

或 nth-child(2)、children 选择器或 'div',但似乎没有任何效果。 jsfiddle 解释了这个问题。

问题 2: 按下子链接后子菜单会折叠,但我希望它不要那样做。 jQuery 事件只能在点击 parent 时触发吗?

问题3:如果点击一个新的菜单点,应该触发新的子菜单的动画,同时旧的子菜单应该折叠。

CSS

.nav {
    width: 200px;
    float: left;
    background-color: yellow;
    color: black;
}
.nav .submenu {
    border: 1px solid transparent;
    height: 0px;
    width: 100%;
    overflow: hidden;
}
.nav .active {
    color: red;
}
.nav .active + .submenu {
    border-color: black;
}
a:hover {
    color: blue !important;
}
a:hover + .submenu {
  border-color: black !important;
}

HTML

<div class="nav">
    <div class="menu">
        <a class="">Menu1</a>
        <div class="submenu">
            <li><a>Submenu1</a></li>
            <li><a>Submenu2</a></li>
        </div>
    </div>
    <div class="menu">
        <a class="">Menu2</a>
        <div class="submenu">
            <li><a>Submenu1</a></li>
        </div>
    </div>
</div>

Javascript

$(document).ready(function(){
    $('.nav .menu a').click(function(){
            $('a').removeClass("active");
            $(this).addClass("active");
    });
});

$(document).ready(function(){
    $('.nav .menu a').click(function () {
        if ($('.submenu').css('height') == '0px') {
            $('.submenu').animate({height:100}, 1000);
            $('.submenu').css("border-color","black");
        } else {
            $('a').removeClass("active");
            $('.submenu').animate({height:0}, 1000,function(){
                $('.submenu').css("border-color","transparent");    
            });
        }
    });
});

here's the jsfiddle

非常感谢您的帮助!我使用这个网站学到了很多东西,但是 JavaScript 甚至连 google 都很难正确 ;)

类似

$('.menu a').on('click',function(){

    //Because of the ordering of your html, you should just use the .next() 
    //to 
    //get the surrounding div that holds  your submenu
    var subMenu = $(this).next();
    //Then go through the children of this list and show, hide, or do 
     //whatever you want to the elements
     $(submenu).childern().each(functon(){
             //style each div accordingly 

       });


 });

如果您只想显示菜单,则不需要获取子项,只需获取点击标签中的 .next()