使用jquery显示/隐藏html ul

Show/Hide html ul with jquery

本文关键字:html ul 隐藏 jquery 显示 使用      更新时间:2023-09-26

单击上一个列表元素时,我正试图显示隐藏的嵌套列表。为此,我想修改html元素的类。我以前没有使用过JavaScript/jQuery,所以我有点困惑如何尝试。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script>
$('li').click(function () {
    if ($(this).next('ul').hasClass("hidden")) {
        $(this).next('ul').removeClass("hidden");
        $(this).next('ul').addClass("visible");
    } else if ($(this).next('ul').hasClass("visible")) {
        $(this).next('ul').removeClass("visble");
        $(this).next('ul').addClass("hidden");
    }
});
</script>
<ul class="year">
    <li>2013</li>
    <ul class="hidden">
        <li>Nov</li>
        <ul class="hidden">
            <li>25</li>
        </ul>
    </ul>
</ul>
<!--Invalid HTML structure fixed, ul should have li elements as its children-->
<ul class="year">
    <li>2013
        <ul class="hidden">
            <li>Nov
                <ul class="hidden">
                    <li>25</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

主要问题是您没有使用dom就绪

//dom ready handler
jQuery(function () {
    $('li').click(function (e) {
        //stop propagation else parent li elements click handlers will get triggered
        e.stopPropagation();
        //use toggleClasss
        $(this).children('ul').toggleClass('hidden visible')
    });
})

然后您可以使用toggleClass来切换类

试试这个

$("id").toggle();

这样就可以了。