简体   繁体   中英

Collapse/Expand Table

I'm looking for a little jquery help to collapse/expand a table that I have on my site. I'd also like the table to start expanded.

Here is an example of a table I have:

<table class="table">
  <caption>
  <div class="video-header">Header</div>
  </caption>
  <tbody>
    <tr class="video-row">
      <td class="field-title"> Content </td>
    </tr>
    <tr class="video-row">
      <td class="field-title"> More Content</td>
    </tr>
  </tbody>
</table>

I'd like it that when you click on the "Header" that it collapses the entire table, not just the row.

I've found the following example , but can't seem to translate it to my case.

Just write a click handler for the caption element

jQuery(function () {
    $('table > caption').click(function () {
        $(this).next().toggle();
    })
})

Demo: Fiddle

because your table is generated dynamically, you should define a parent node in which the table is located. this parent node should always exist in the page and should NOT be generated dynamically.

  <div id="table-container">
    <table class="table">
      <caption>
      <div class="video-header">Header</div>
      </caption>
      <tbody>
        <tr class="video-row">
          <td class="field-title"> Content </td>
        </tr>
        <tr class="video-row">
          <td class="field-title"> More Content</td>
        </tr>
      </tbody>
    </table>
  </div>

then bind click event on that parent node.

$("#table-container caption").on("click", function(){
  $("#table-container table").css("display", "none");
});

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