展开&折叠div不封装HTML表

时间:2018-03-27 09:12:46

标签: javascript jquery html css

我有这段代码:

$(".header").click(function() {
  $('.content').slideToggle().toggleClass('active');
  if ($('.content').hasClass('active')) {
    $('.header span').text('Collapse');
  } else {
    $('.header span').text('Expand');
  }
});
$('button').click(function(){
    $(".header").trigger('click');
})
.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>I'm putting a search bar here.</li>

        </ul>
    </div>
</div>
  <button>another click</button>

当我将HTML部分更改为此时(在隐藏的div内添加一个表):

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>I'm putting a search bar here.</li>

             <table>
             <tr><td>a</td></tr>
             <tr><td>b</td></tr>
             <tr><td>c</td></tr>
             </table>
        </ul>
    </div>
</div>
  <button>another click</button>

该表格从div开始,即在div下方,并且未隐藏。如何在div内查看该表?提前谢谢。

1 个答案:

答案 0 :(得分:0)

这是您的预期结果,请查看下面的代码段:

&#13;
&#13;
$(".header").click(function() {
  $('.content').slideToggle().toggleClass('active');
  if ($('.content').hasClass('active')) {
    $('.header span').text('Collapse');
  } else {
    $('.header span').text('Expand');
  }
});
$('button').click(function(){
    $(".header").trigger('click');
})
&#13;
.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
     <p>I'm putting a search bar here.</p>
     <table>
       <tr><td>a</td></tr>
       <tr><td>b</td></tr>
       <tr><td>c</td></tr>
      </table>
    </div>
</div>
  <button>another click</button>
&#13;
&#13;
&#13;