【问题标题】:Hide all next tr td until next tr th隐藏所有下一个 tr td 直到下一个 tr th
【发布时间】:2012-07-10 00:38:49
【问题描述】:

应该很简单,但是这个 jQuery 函数占用了很多元素,它甚至隐藏了我认为的 jQuery。

我想做的是,当一个人点击 tr th 时,所有下一个 tr td 都应该隐藏到下一个 tr th.

我怎样才能让这段代码工作?

    <!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <style>
th {  background:#dad;
      font-weight:bold;
      font-size:16px; 
      width: 50%;
}
td {  background:red;
      font-weight:bold;
      font-size:16px; 
      width: 50%;
}
</style>
</head>
<body>
  <table id="example">
    <tr>
      <th>
        <button>Show it 3</button>
      </th>
    </tr>
    <tr>
      <td>test 1</td>
    </tr>
    <tr>
      <td>test 2</td>
    </tr>
    <tr>
      <th>
        <button>Show it 2</button>
      </th>
    </tr>
    <tr>
      <td>test 3</td>
    </tr>
    <tr>
      <td>test 4</td>
    </tr>
  </table>

    <script>
      $('#example tr th').click( function() {
        //alert($(this).parent().html())
        $(this).parent().nextUntil('tr th').toggle();
      })
    </script>
</body>
</html>

【问题讨论】:

    标签: jquery toggle show-hide


    【解决方案1】:

    您可以向具有th 元素的tr 元素添加一个类:

    <table id="example">
        <tr>
          <th class='toggle'>
            <button>Show it 3</button>
          </th>
        </tr>
        <tr>
          <td>test 1</td>
        </tr>
        <tr>
          <td>test 2</td>
        </tr>
        <tr class='toggle'>
          <th>
            <button>Show it 2</button>
          </th>
        </tr>
        <tr>
          <td>test 3</td>
        </tr>
        <tr>
          <td>test 4</td>
        </tr>
      </table>
    

    $('#example tr th').click( function() {
       $(this).parent().nextUntil('.toggle').toggle();
    })
    

    DEMO

    【讨论】:

    • 谢谢。我使用了你的解决方案,因为它很简单。
    【解决方案2】:

    这是一种主要使用 dom 的方法

      $('#example tr td button').on('click',function(e){
           var curr = this;
           // get the tr where the button was clicked
           while(curr.nodeType!=='tr') curr = curr.parentNode;
           // now get sibling nodes
           while((curr=curr.nextSibling)){
               if(curr.firstChild.nodeType==='td') $(curr).hide();
               else if(curr.firstChild.nodeType==='tr') return;
           }
        }
    

    或者,使用更多 jQuery:

    $('#example tr td button').on('click',function(e){
        var siblings = $(this).siblings();
        for(var i=0; i < siblings.length; i++){
            if(siblings[i].find('td').length) $(siblings[i]).hide();
            else if(siblings[i].find('tr').length) return;
        }
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多