Click on subitem of the menu brings id of the level above

1

I'm making a menu where when I click on it I send a code to a page, this page it redirects to the page that was set with that id . Until this point it is working only that when I click on the submenu, it brings me the code of his father.

carregarPaginas();

function carregarPaginas() {
    $(".subitem").click(function(e) {
        e.preventDefault();

        var acao = $(this).find('.acao').html();
        location.href = 'includes/publicacao.php?c=' + acao;
    });

    $(".menuLi").click(function(e) {
        e.preventDefault();

        var acao = $(this).find('.acao').html();
        location.href = 'includes/publicacao.php?c=' + acao;
    });
};

Here comes the menu structure:

<li class="menuLi">
    <div class="acao">-3</div>
    <div class="desc">Servicos</div>
    <div class="submenuC">
        <ul class="submenu">
            <li class="subitem">
                <div class="acao">-4</div>
                <div class="desc">Downloads</div>
            </li>
            <li class="subitem">
                <div class="acao">-5</div>
                <div class="desc">Videos</div>
            </li>
        </ul>
    </div>
</li>
    
asked by anonymous 10.07.2015 / 15:22

2 answers

4

When you click on the child element, the event goes up in the DOM and also fires the click event on the parent ( .menuLi ).

So you have to prevent it from spreading with e.stopPropagation(); and therefore do not trigger the event of the parent element.

The code looks like this:

$('.subitem').click(function(e){
    e.stopPropagation();
    // resto do código...
    
10.07.2015 / 15:33
3

The problem is that when you click on a subitem, you are also clicking the menu. Therefore, you expect to validate the clicked item

carregarPaginas();

            function carregarPaginas() {
                $(".subitem").click(function (e) {
                    e.preventDefault();

                    var acao = $(this).find('.acao').html();
                    location.href = 'includes/publicacao.php?c=' + acao;
                });

                $(".menuLi").click(function (e) {
                    e.preventDefault();
                    if(ehDescendenteDeSubItem(e.target)) return;

                    var acao = $(this).find('.acao').html();
                    location.href = 'includes/publicacao.php?c=' + acao;
                });
            }

function ehDescendenteDeSubItem(e){
    return $(e).parent().attr('class') === 'subitem'
}
    
10.07.2015 / 15:36