1

I've got a slide menu that seems to be working fine, the thing is if you select a link it works as it should do, if you select a link that has a child then the preventdefault() kicks in and it scrolls to it's child, i'm happy so far, but once you get to the end of the links as there's no more children, the link should work as normal but it doesn't.

here's the jquery

$(".menu li").click(function(e) {
    if($(this).children('.sub-menu').length > 0) {
        e.preventDefault();
        $(this).children('.sub-menu').addClass('open');
    }
    else  {
        $(".menu li").ready(function(){
            return true;
        });
    }
});

i've also attached a fiddle of it working.

http://jsfiddle.net/R6wHG/16/

4

2 回答 2

5

问题是您将事件处理程序绑定到<li>元素,并且单击<a>元素会传播到 DOM。当您单击链接时,它会从该链接冒泡到<li>(不包含子菜单),然后最终上升到另一个<li>确实包含子菜单的链接,此时单击的默认行为事件(按照链接)被抑制。将您的事件处理程序绑定到<a>元素本身,并检查下一个元素是否为.sub-menuone:

$(".menu a").click(function (e) {
    if ($(this).next('.sub-menu').length > 0) {
        e.preventDefault();
        $(this).next('.sub-menu').addClass('open');
    }
});

更新了 jsFiddle

于 2013-10-17T12:14:34.817 回答
3

您还需要stopPropagation()preventDefault()li元素上调用:

$(".menu li").click(function (e) {
    e.stopPropagation();
    if ($(this).children('.sub-menu').length > 0) {
        e.preventDefault();
        $(this).children('.sub-menu').addClass('open');
    }
});

示例小提琴

注意我也删除return true了,因为它是多余的。

于 2013-10-17T12:14:28.677 回答