Levi
Levi

Reputation: 309

Why jQuery applies click prevent to all of my list elements

I am building a multi-level drop down

HTML

<div id="sidebar" class="sidebar-left">
    <ul class="downlod-categories">
        <li class="cat-item cat-item-31">
            <a title="Kategória 1 kategória összes bejegyzése" href="?dlm_download_category=kategoria-1">Kategória 1</a>
            <ul class="children" style="display: block;">
                <li class="cat-item cat-item-32">
                <li class="cat-item cat-item-35">
                <li class="cat-item cat-item-36">
                    <a title="Alkategoria 3 kategória összes bejegyzése" href="?dlm_download_category=alkategoria-3">Alkategoria 3</a>
                </li>
            </ul>
        </ul>   
    </li>

jQuery

$('#sidebar ul.downlod-categories li').each(function(){
    var child = $(this).children('ul.children');

    if(child.length)
    {
        $(this).on('click', function(e){
            e.preventDefault();
            child.show();
        });
    }
});

And my problem is, if an actual li has children, the prevent default works, but it applies, for all children elements as well.

Could please someone give me a hint, or point out what i am doing wrong?

Upvotes: 0

Views: 55

Answers (2)

Levi
Levi

Reputation: 309

Thanks for all of your replies, this worked

Instead of

$(this).on('click', function(e){
                e.preventDefault();
                child.show();
            }); 

I had to use

if(child.length)
        {
            $(this).children('a').on('click', function(e){
                e.preventDefault();
                child.show();
            }); 
        }

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

Change your selector like this -

$('#sidebar ul.downlod-categories > li')

Upvotes: 2

Related Questions