expand/collapse table rows with JQuery

后端 未结 7 918
闹比i
闹比i 2020-11-27 11:09

I want to expand and collapse table rows when header columns is clicked. I only want to expand/collapse rows which are under the specific header (clicked).

Here is m

相关标签:
7条回答
  • 2020-11-27 11:46

    I liked the simplest answer provided. However, I didn't like the choppiness of the collapsing. So I combined a solution from this question: How to Use slideDown (or show) function on a table row? to make it a smoother animation when the rows slide up or down. It involves having to wrap the content of each td in a div. This allows it to smoothly animate the collapsing. When the rows are expanded, it will replace the div, with just the content.

    So here's the html:

    <table>
    <tr class="header">
        <td>CARS</td>
    </tr>
    <tr class="thing">
        <td>car</td>
    </tr>
    <tr class="thing">
        <td>truck</td>
    </tr>
    <tr class="header">
        <td>HOUSES</td>
    </tr>
    <tr class="thing">
        <td>split level</td>
    </tr>
    <tr class="thing">
        <td>trailer</td>
    </tr>
    

    And here's the js

    $('.header').click(function(){
    if($(this).hasClass("collapsed")){
        $(this).nextUntil('tr.header')
        .find('td')
        .parent()
        .find('td > div')
        .slideDown("fast", function(){
            var $set = $(this);
            $set.replaceWith($set.contents());
        });
        $(this).removeClass("collapsed");
    } else {
        $(this).nextUntil('tr.header')
        .find('td')
        .wrapInner('<div style="display: block;" />')
        .parent()
        .find('td > div')
        .slideUp("fast");
        $(this).addClass("collapsed");
    }
    });
    

    Checkout this fiddle for an example https://jsfiddle.net/p9mtqhm7/52/

    0 讨论(0)
提交回复
热议问题