嵌套的单击子事件,父事件触发事件 [英] nested li - on clicking child, parent click event triggered

查看:133
本文介绍了嵌套的单击子事件,父事件触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的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();
    }
}

我想为父类调用不同的函数,

I want different functions to be called for the parent and child li.But now when the child is clicked it triggers the parent.

提前感谢

推荐答案

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

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

Since the structure is the same for both menu levels, I would attach a single handler to the to top menus container and test whether the click accured against a <a> tag (followed by an ul element) or not then if true process the sibling menu.

喜欢这样。

/* 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

这篇关于嵌套的单击子事件,父事件触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆