简体   繁体   中英

Jquery Slide up and Slide down toggle

I am working with ASP.NET MVC 4. I have a nested list in my razor view like so:

<ul class="nav" id="product-cat-menu">
    <li><a href="/Products/Index?category=2002">Dental <i class="fa fa-plus-square-o rightdown"></i></a>
        <ul>
            <li><a href="/Products/Index?category=2004">Materials <i class="fa fa-plus-square-o rightdown"></i></a>
                <ul>
                    <li><a href="/Products/Index?category=2011">Pulp<i class="fa fa-plus-square-o rightdown"></i></a></li>
                    <li><a href="/Products/Index?category=3011">Etchants <i class="fa fa-plus-square-o rightdown"></i></a>
                </ul>
                <li><a href="/Products/Index?category=2006">Medicines <i class="fa fa-plus-square-o rightdown"></i></a>
                    <ul>
                        <li><a href="/Products/Index?category=2011">Pulp<i class="fa fa-plus-square-o rightdown"></i></a></li>
                        <li><a href="/Products/Index?category=3011">Etchants <i class="fa fa-plus-square-o rightdown"></i></a>
                    </ul>
                </li>
        </ul>
    </li>
    <li><a href="/Products/Index?category=2003">Oral <i class="fa fa-plus-square-o rightdown"></i></a></li>
</ul>

And the main CSS is:

#product-cat-menu li {
    cursor: pointer;
    position: relative;
}

#product-cat-menu li .rightdown {
    position: absolute;
    right: 0;
}

#product-cat-menu ul {
    display: none;
}

#product-cat-menu li ul li {
    padding: 5px 0 5px 25px;
    width: 100%;
}

And jQuery is like:

$(document).ready(function () {
    $("#product-cat-menu a").click(function () {
        $("#product-cat-menu ul").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown();
        }
    });
});

The problem is that when clicking on the li it slides down the child list but after going to the controller action it is slides up. I want show the slide down part after the page refreshing.

For that i am trying the following code also:

$(document).ready(function () {
    $("#product-cat-menu a .rightdown").click(function() {
        //...........
    });
});

but this is not working.

I believe you need to prevent the default behaviour of the html anchor tag ( <a> ) occurring.

The line that is missing is:

evt.preventDefault();

The full code example is as follows:

$(document).ready(function () {
    $("#product-cat-menu a").click(function (evt) {
        evt.preventDefault();
        $("#product-cat-menu ul").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown();
        }
    });
});

You can see this in a JSFiddle here: DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM