javascript 使用 jQuery 切换表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13450771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:49:05  来源:igfitidea点击:

Toggle table row with jQuery

javascriptjqueryhtml-tablerowtoggle

提问by weezle

I have a table where I click on a parent row which shows/hides child row with certain CSS class. The thing is that .toggle() is triggered with a click on a parent row and I would like to be triggered only by clicking on span with a class btn which is inside parent row.

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

This is HTML:

这是 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>

This jQuery:

这个jQuery:

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

Here is jsfiddle link

这是jsfiddle链接

回答by Henrik Andersson

You can change the selector to

您可以将选择器更改为

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

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

this will get you any spanwith the class buttonin a tdthat is in a trwith the class parent

这将让你的任何span与类buttontd是一个tr带班parent

UPDATE

更新

If the table is created dynamically you can use the on()function instead of a click, if i'm understanding you right.

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

I see what you mean, even though your question doesnt reflect it. I updated the fiddle for you.

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

This is the jquery that you want:

这是您想要的 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

请参阅此处的小提琴

回答by Bruno

Try:

尝试:

$("tr.parent > td").on( "click", "span.btn", function() {

    var childId = $(this).parents("tr").prop("id");
    $("tr.child-" + childId).toggle("slow");
});

Fiddle here

在这里摆弄

回答by Murali Murugesan

Try it with on()

on()试试

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