javascript preventDefault only on parent item

蹲街弑〆低调 提交于 2020-02-06 05:53:25

问题


I am creating a drop down nav in javascript. Any list items that have children i would like to prevent the default action and do something else. I have this working but when applied the default action is also applied to the child list items.

Here is my HTML:

<i id="mobnavtrig" class="fa fa-align-justify fa-2x"></i>
    <div class="mobilenav">
        <li class="page_item page-item-2"><a href="/">Home</a></li>
        <li class="page_item page-item-10"><a href="?page_id=10">Who We Are</a></li>
        <li class="page_item page-item-25 page_item_has_children current_page_item parent"><a href="?page_id=25">Case Studies</a>
            <ul class='children'>
                <li class="page_item page-item-55"><a href="?page_id=55">Barratt Developments</a></li>
                <li class="page_item page-item-53"><a href="?page_id=53">Care in Bathing</a></li>
            </ul>
        </li>
        <li class="page_item page-item-27"><a href="?page_id=27">Blog</a></li>
        <li class="page_item page-item-29"><a href="?page_id=29">Get In Touch</a></li>
    </div>

Here is my JS:

$( ".mobilenav li.parent" ).click(function(event) {
        if($(this).hasClass('page_item_has_children')){
            event.preventDefault( );
            $(this).addClass('current_page_item');
            $(this).find('.children').slideToggle("fast");
        }
    });

Is there something i am missing in the above?


回答1:


in children click you have to use stopPropagation() to stop event bubbling

$( ".mobilenav li.parent .children" ).click(function(e){
  e.stopPropagation();

});



回答2:


I think you want this:

$('.mobilenav li.parent > a').click(function(e) {
    e.preventDefault();
});

The > only matches immediate children of the previous tag.

This will definitely work:

$('.mobilenav li.parent').on('click', "a", function(e) {
    e.preventDefault();
});


来源:https://stackoverflow.com/questions/27245600/javascript-preventdefault-only-on-parent-item

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