简体   繁体   中英

How to hide the rows in the table by clicking on button toggle

I want to hide the rows with data under the row with header and button until next the row with header and button. clicking one of the +/- button hides/expands all the rows with data content. http://jsfiddle.net/9ekhuj1q/ Please find the code below-

<table border="0">
  <tr>
    <th>Data1</th>
    <th>Data2</th>
  </tr>
  <tr  class="header expand">
      <td ><button class="url-button">
      <span class="sign"></span>
      </button></td>
      <td>Header </td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr  class="header expand">
      <td ><button class="url-button">
      <span class="sign"></span>
      </button></td>
      <td>Header </td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

styling

table, tr, td, th
{
    border: 1px solid black;
    border-collapse:collapse;
}
tr.header
{
    cursor:pointer;
}
.header .sign:after{
  content:"+";
  display:inline-block;      
}
.header.expand .sign:after{
  content:"-";
 }

Click function-

$('.url-button').click(function(){
     $('.header').toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});

Currently you are selecting all elements with the header class whenever you click one of the buttons with $('.header') . But you'll want to select the element with the header class that is a grandparent of the button you've just clicked.

Use the this keyword to refer to the element you are listening on with the click() event listener. That element will be the button that you've clicked on. From there you want to select the element with the header class that is a parent of the button using .parent('.header') . Now you've selected the correct element and not all the elements with the class.

$('.url-button').click(function() {
  $(this)
    .parents('.header')
    .toggleClass('expand')
    .nextUntil('tr.header')
    .slideToggle(100);
});

Another similar way to do the job is to use event.target :

  $('.url-button').click(function(event){ 
    $(event.target)
      .closest('tr')
      .toggleClass('expand')
      .nextUntil('tr.header')
      .slideToggle(100);
  });

There are arguments for either one, but I prefer to use event.target over this , because it makes the object that this refers to immediately obvious. In any case, your original code is selecting all elements with a .header class, which as Emiel points out is the source of your problem.

Also, closest and parents have the same behavior in this case. (If you are interested in how they differ, have a look at this .)

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