简体   繁体   中英

Expanding and collapsing table rows in jQuery

Here is the jQuery code for expanding and collapsing the rows in a table but it just doesn't seem to work. Am I going wrong anywhere ?

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

The following is the jsFiddle

https://jsfiddle.net/uxc3fkcm/

You have over complicate it. Simply use $.fn.toggleClass() and $.fn.toggle()

$('.Complex').click(function () {
    $(this).toggleClass("collapsed").nextUntil('tr.Complex').toggle();
});

DEMO

If you want sliding motion then use $.fn.slideToggle() instead of $.fn.toggle()

Display or hide the matched elements with a sliding motion.

you have written .parent() after else case and use display none; instead of display block;

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

Maybe try This :D

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

 $(function () {
     $("td[colspan=3]").find("p").hide();
     $("table").click(function (event) {
         event.stopPropagation();
         var $target = $(event.target);
         $target.closest("tr").nextAll().find("p").slideToggle();

     });
 });

worked for me hopefully works for you 2 :D

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