【问题标题】:Toggle table row with jQuery使用 jQuery 切换表格行
【发布时间】:2012-11-19 09:21:40
【问题描述】:

我有一个表,我在其中单击父行,该行显示/隐藏具有特定 CSS 类的子行。 问题是 .toggle() 是通过单击父行触发的,我只想通过单击父行内的类 btn 的 span 来触发。

这是 HTML:

<table cellpadding="5" cellspacing="3" border="1">
  <tbody>
    <tr class="parent" id="2479">
      <td><span class="btn">text</span></td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr class="child-2479">
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
    </tbody>
</table>

这个 jQuery:

$(function() {
    $('tr.parent')
        .click(function(){
            $(this).siblings('.child-'+this.id).toggle('slow');
        });
    $('tr[class^=child-]').hide().children('td');
});

这里是jsfiddle link

【问题讨论】:

    标签: javascript jquery html-table row toggle


    【解决方案1】:

    您可以将选择器更改为

    $('tr.parent td span.btn').click(function(){...});

    这将为您提供 td 中的 buttonbutton 中的任何 trparent 中的 tr

    更新

    如果表格是动态创建的,您可以使用on() 函数而不是单击,如果我理解正确的话。

    我明白你的意思,即使你的问题没有反映出来。 我为你更新了小提琴。

    这是你想要的 jquery:

    $(function() {
        $('tr.parent td')
            .on("click","span.btn", function(){
                var idOfParent = $(this).parents('tr').attr('id');
                $('tr.child-'+idOfParent).toggle('slow');
            });
    });
    

    See the fiddle here

    【讨论】:

    • 事情是父子行是动态创建的。父行 ID(在本例中为 2479)是子行类(child-2479)的基础。所以我必须从父行 ID 中读取这个数值,并仅在包含该 ID 的类的子行上触发切换。
    • 效果很好!我刚刚添加了这一行: $('tr[class^=child-]').hide().children('td');这是最后一个例子:jsfiddle
    • 你可以用 CSS 来隐藏它,让你的 JS 不那么混乱,只是一个提示! :)
    • 此答案不适用于动态添加的表行,因为事件处理程序已附加到现有的 span.btn 元素。
    • 更新了答案,使其正确反映 api 并附加当前和未来的元素。 :) 不错的赶上@Bruno! :)
    【解决方案2】:

    试试:

    $("tr.parent > td").on( "click", "span.btn", function() {
    
        var childId = $(this).parents("tr").prop("id");
        $("tr.child-" + childId).toggle("slow");
    });
    

    小提琴here

    【讨论】:

      【解决方案3】:

      试试 on()

       $("body").on("click", "tr span.btn", function(event){
           $(this).siblings('.child-'+this.id).toggle('slow');
       });
      

      【讨论】:

        猜你喜欢
        • 2011-07-04
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-28
        • 1970-01-01
        • 1970-01-01
        • 2013-06-11
        相关资源
        最近更新 更多