expand/collapse table rows with JQuery

后端 未结 7 985
闹比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:

    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('
    ') .parent() .find('td > div') .slideUp("fast"); $(this).addClass("collapsed"); } });

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

    提交回复
    热议问题
    CARS
    car
    truck
    HOUSES
    split level
    trailer