使用更优雅的解决方案扩展/折叠多个表行 [英] Expand/collapse multiple table rows with a more elegant solution

查看:125
本文介绍了使用更优雅的解决方案扩展/折叠多个表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中有多个包含数据的表.

I have a page where I have multiple tables with data.

提琴:

DEMO

<th>位于具有类名称的<tr>中,并且每一行都有类似的命名...

The <th> is in a <tr> with a class name and each of the rows have similar naming...

rowToClick1 rowToClick2

...等等.

在for循环中,我动态地生成数据-我有<tr>,其类名和上面类似,它们被命名为...

Inside a for loop, where I generate data dynamically - I have <tr>'s with class names and similar to above they are named...

rowToExpand1 rowToExpand2

...等等.

当前,我的解决方案适用于扩展/折叠这些表,但确实难看:

Currently, my solution is working for expanding/collapsing these tables, but it is really ugly:

$('.rowToClick1').click(function () {
    $(this).find('span').text(function (_, value) {
        return value == '-' ? '+' : '-';
    });
    $(".rowToExpand1").toggle();
});

$('.rowToClick2').click(function () {
    $(this).find('span').text(function (_, value) {
        return value == '-' ? '+' : '-';
    });
    $(".rowToExpand2").toggle();
});

// Many more similar functions repeatedly, up to 20+ ..

我如何才能更有效地做到这一点?

How can I do this more efficiently?

注意:我不希望表格同时展开/折叠,而要单独展开(如我现在这样做).

Note: I don't want the tables to expand/collapse at the same time, but individually (like I do now).

谢谢.

推荐答案

我建议:

// binding the event to the 'th':
$('th').click(function () {
    // finding the contained 'span' element, manipulating its text (as before):
    $(this).find('span').text(function (_, value) {
            return value == '-' ? '+' : '-';
        // finding the closest 'thead' (in which the 'th' elements are contained:
        }).closest('thead')
        // finding the sibling 'tbody' element:
        .next('tbody')
        // finding the 'tr' descendants:
        .find('tr')
        // toggling their visibility:
        .toggle();
});

JS Fiddle演示.

如果您只有一个 <tbody>元素,则上述方法适用;如果您应该有多个元素该方法不起作用(由于使用了);如果(可能)有更多的<tbody>元素,则可以改用nextAll():

The above works if you have only one <tbody> element; if you should have multiple elements that approach doesn't work (due to the use of next()); should there be (potentially) more <tbody> elements then you could instead use nextAll():

$('th').click(function () {
    $(this).find('span').text(function (_, value) {
            return value == '-' ? '+' : '-';
        }).closest('thead').nextAll('tbody').find('tr').toggle();
});

JS Fiddle演示.

参考文献:

  • click().
  • closest().
  • find().
  • next().
  • nextAll().
  • toggle().

这篇关于使用更优雅的解决方案扩展/折叠多个表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆