简体   繁体   中英

Traversing through a list with jQuery

My list structure is something like this:

<ul class="nav-list">
        <li class="nav-list-item first-stage">
          <a href="">
            <table>
                <tr>
                    <td class="first">Stuff</td>
                    <td class="second"><i class="fa fa-chevron-down"></i></td>
                </tr>
            </table>
          </a>
        </li>
    <ul class="inner-nav">
            <li class="nav-list-item second-stage selected">
              <a href="">
                <table>
                    <tr>
                        <td class="inner-first"><div class="icon icon-arrow-right"></div></td>
                        <td class="inner-second">Blaa</td>
                    </tr>
                </table>
               </a>
            </li>

Here's my jQuery:

if $(".first-stage").click(function() {
    var nextItem = $(this).next("li").chidren(".second-stage").find("i");
    if ($(this).next(".inner-nav").is(":hidden")) {
        $(this).slideDown();
        $(nextItem).removeClass(".fa-chevron-down").addClass(".fa-chevron-up");
    } else {
        $(this).slideUp();
        $(nextItem).removeClass(".fa-chevron-up").addClass(".fa-chevron-down");
    }
)};

I can't get the traversing through the list to work. This is supposed to be a dropdown list. Don't mind about the "a href" around li.

Firstly, you need to amend your HTML to make it valid:

<ul class="nav-list">
    <li class="nav-list-item first-stage">
        <table>
            <tr>
                <td class="first">Stuff</td>
                <td class="second"><i class="fa fa-chevron-down"></i></td>
            </tr>
        </table>
        <ul class="inner-nav">
            <li class="nav-list-item second-stage selected">            
                <a href="">
                    <table>
                        <tr>
                            <td class="inner-first"><div class="icon icon-arrow-right"></div></td>
                            <td class="inner-second">Blaa</td>
                        </tr>
                    </table>
                </a>
            </li>
        </ul>
    </li>
</ul>

Then you can simplify your jQuery code by using slideToggle and toggleClass :

$(".first-stage").click(function(e) {
    var $nextItem = $('ul', this);
    var $i = $('i', this);
    $nextItem.slideToggle(function() {
        $i.toggleClass('fa-chevron-down fa-chevron-up');
    });
});

Example fiddle

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