繁体   English   中英

使用JQuery选择标头之间的所有表行

[英]Select all table rows between headers using JQuery

具有以下自动生成的表格布局(我几乎没有影响它)

<table>
   <tr>
      <th>First Header</th>
      <th>
         <a href="#" class="used-for-some-action">show/hide</a>
      </th>
   </tr>
   <tr>
      <td>A question?</td>
      <td><input value="User's answer" /></td>
   </tr>
   <!-- Some more rows -->

   <tr>
      <th>Second Header</th>
   </tr>

   <!-- Some more question blocks -->
</table>

...我想使用Javascript / jQuery选择两个标头之间的所有<tr>元素,以便提供如下功能:

  • 隐藏属于某个标题的所有问题。
  • 自动编辑<input>例如,全部选中/取消选中恢复默认值)

导致所需操作的链接已在正确的标题中。

解决这个问题的最佳方法是什么?

您可以使用nextUntil()来解决此问题。

function getRows(start){
    return start.nextUntil(function(i, v){
        return $('th', v).length > 0;
    });
}

演示: 小提琴

显示/隐藏的实现

$('table').on('click', '.used-for-some-action', function(){
    getRows($(this).closest('tr')).toggle();
    return false;
});

演示: 小提琴

更新:
根据@BLSully的评论

$('table').on('click', '.used-for-some-action', function(){
    $(this).closest('tr').nextUntil('tr:has(th)').toggle();
    return false;
});

演示: 小提琴

我喜欢Arun P Johny的回答。 这就是我最初的想法(此代码实现了隐藏/显示功能)

$(".used-for-some-action").click(function(e) {
    e.preventDefault()

    $(this).parents("tr").next().is(":visible") ? $(this).parents("tr").next().hide() : $(this).parents("tr").next().show();
});

小提琴: http : //jsfiddle.net/DQMht/1/

我会保持简单。 您正在使用JavaScript,因此在页面加载时,只需将类添加到带有<th>行,然后使用该类。

$(function() {
    $("th").parent().addClass("hasTH");
});

然后,您可以简单地定位具有hasTH类的行。


另一种选择是在页面加载时仍然执行此操作,但不是添加类,而是将行分组为新的<tbody>元素。 这将为您提供最纯粹的DOM表示。

尝试这个:

$("tr:has(th)").each(function(){
    if ($(this).find('th').length==2) {
        // here you have this: that represent the row which have two td
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM