The code opens all the submenus when you click the primary menu li item

PHP code generates a navigation menu for this structure -

<ul class="menu">
    <li><a href="link">LINK 1</a></li>
    <li><a href="link">LINK 2</a>     <!-- click disabled -->  
        <ul class="sub-menu">
            <li><a href="link">LINK 3</a></li>
            <li><a href="link">LINK 4</a></li>
        </ul>
    </li>
    <li><a href="link">LINK 5</a></li>
    <li><a href="link">LINK 6</a>     <!-- click disabled -->
        <ul class="sub-menu">
            <li><a href="link">LINK 7</a></li>
            <li><a href="link">LINK 8</a></li>
            <li><a href="link">LINK 9</a></li>
        </ul>
    </li>
    <li><a href="link">LINK 10</a></li>
    <li><a href="link">LINK 11</a></li>
</ul>

Instead of opening sub-menuwith hover, I want to open it using click
jQuery for click:

$(document).ready(function(){
    var li = $('.menu>li',this).has('.sub-menu');
    $('>a',li).click(function(e){
        e.preventDefault();
        $('.sub-menu',li).toggle();
    });
});

The only problem is that when clicked, everything opens ulwith the class .sub-menu. I want the snap tag of the sub-menucurrent click to snap. How to do it?

+4
source share
3 answers

Try the following:

Working example https://jsfiddle.net/cjvwkvq9/

$("li > a")
    .on("click", function (e) {
    $(e.target).next().toggle();
});

Where $(e.target)is the item with a click.

+2
source

this? '.sub-menu',li this. : https://api.jquery.com/click/

0

The most efficient code in this case should consist of one handler in <ul>, and not for adding event listeners to all <li>.

$('ul.menu').on('click', 'li', function(e){
    var target = $(e.target);
    ...and so on ...
});
0
source

All Articles