简体   繁体   中英

Toggle table rows with jquery

I have a normal html table.

Each <tr> has attributes data-id and data-parent-id .

I want to toggle underlying <tr> when I click on a <tr> .

I have made a short bad solution:

$("tr[data-id]").click(function () {
    var id = $(this).attr("data-id"); // get id from clicked tr

    $(this).siblings('tr[data-parent-id="' + id + '"]').each(function () { // iterate through all tr under clicked tr
        $(this).toggle(); // toggle first level under clicked tr
        var id = $(this).attr("data-id"); // get id from first level under clicked tr

        $(this).siblings('tr[data-parent-id="' + id + '"]').each(function () { // iterate through all tr under first level under clicked tr
            $(this).toggle(); // toggle _second level_ under clicked tr
            var id = $(this).attr("data-id"); // get id from _second_ level under clicked tr

            $(this).siblings('tr[data-parent-id="' + id + '"]').each(function () { // iterate through all tr under second level under clicked tr
                $(this).toggle(); // toggle _third_ level under clicked tr
            });
        });
    });
});

In my example I loop through each level but I don't know how to make a "never ending" traversing. I have specified only 3 levels of <tr> but it should be limitless.

It seems that http://ludo.cubicphuse.nl/jquery-treetable/ does what I want but I think it could be done much simpler and when I have a huge table I think it's better to hide the collapsed table rows with css instead of waiting for the javascript to do this (it flickers because of the loading).

How can I make a loop that checks for every <tr> if any other <tr> has its data-id as data-parent-id ?

Edit :

Html

<table>
  <tbody>
    <tr data-id="1" data-parent-id=""></tr>
    <tr data-id="2" data-parent-id="1"></tr>
    <tr data-id="3" data-parent-id="1"></tr>
    <tr data-id="4" data-parent-id="3"></tr>
    <tr data-id="5" data-parent-id="4"></tr>
  </tbody>
</table>

You need recursivity :

$("tr[data-id]").click(function () {
    Expand($(this).attr("data-id"));
}

function Expand(id)
{
     $('tr[data-parent-id="' + id + '"]').each(function () {
         $(this).toggle();
         Expand($(this).attr("data-id"));
     });
}

You got to be carefull with recursivity cause it may create and endless loop. In this case it will stop when it will reach a tr that as no data-parent-id (the root).

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