嵌套li - 点击子,触发父点击事件

时间:2014-04-01 09:55:02

标签: javascript jquery html css

我有一个嵌套的li

<li class="innerMenuLi"><a href="#"><span>MainLi</span></a>
<ul class="mainMenu">
    <li><a href="#" class="active"><span>mainMenu1</span></a></li>
    <li><a href=""><span>mainMenu2</span></a></li>
    <li><a href=""><span>mainMenu3</span></a></li>
    <li><a href=""><span>mainMenu4</span></a></li>
    <li><a href=""><span>mainMenu4</span></a></li>
    <li class="secondInnerMenu"><a href="#"><span>mainMenu5</span></a>
        <ul class="analyticsMenu">
            <li><a href="">secondInnerMenu1</a></li>
            <li><a href="">secondInnerMenu2</a></li>
            <li><a href="">secondInnerMenu3</a></li>
            <li><a href="">secondInnerMenu4</a></li>
        </ul>
    </li>
</ul>

$('.innerMenuLi').children('.mainMenu').click(function(e){
    e.stopPropagation();
    showMenu($(this));
});
$('.innerMenuLi').click(function(e){
    showMainMenu($(this));
    e.stopPropagation();
});
function showMainMenu(el){
    if(!el.hasClass('open')){
        (el).addClass('open');
        (el).children('.mainMenu').show();
    }else{
        (el).removeClass('open');
        (el).children('.mainMenu').hide();
    }
}
function showMenu(el){
    if(!el.hasClass('open')){
        (el).addClass('open');
        (el).children('.analyticsMenu').show();
    }else{
        (el).removeClass('open');
        (el).children('.analyticsMenu').hide();
    }
}

我希望为父和子li调用不同的函数。但是现在当单击子项时它会触发父项。

提前致谢

1 个答案:

答案 0 :(得分:1)

// will prevent the event to bubble up the DOM and so avoid parent attached handlers to be triggered
e.stopPropagation();

由于两个菜单级别的结构相同,我会将一个处理程序附加到顶部菜单容器,并测试点击是否符合<a>标记(后跟ul元素) if true处理兄弟菜单。

喜欢这样..

/* Event delegation menu click */
$('#root').on('click', function(e){
    var $t = $(e.target).closest('a'),
        $ul = $t.nextAll('ul').eq(0);
    if($t.length && $ul.length){
        $ul.toggleClass('open').slideToggle();
    }
});

fiddle Here