响应式表设计:使用JQuery使click()展开tr

Responsive table design: Make click() expand tr using JQuery

本文关键字:click tr 展开 JQuery 使用 响应      更新时间:2023-09-26

我希望网页上的表能做出相应的行为。这个想法是,一旦页面宽度低于某个阈值,它们就会自动表示为手风琴。我从这一页中提取了手风琴的示例代码。

我现在的问题是,整排桌子都变成了一个按钮,可以触发相应的折叠/展开。如何重新连接js,使<i>元素负责接收点击事件,而不是<tr>元素?

我想要这种行为的原因很简单:我的表包含几个input元素,这一点不能再使用了,因为一旦点击这些输入,表就会折叠回去。

这是我的尝试。然而,它会折叠/展开每一行,而不是只折叠用户点击的那一行:

trAcc.find('i').click(function () {
    if (trAcc.hasClass('accordion-opened')) {
        trAcc
          .animate({ maxHeight: '50px' }, 200)
          .removeClass('accordion-opened');
        $(this).text('+');
    } else {
        trAcc
          .animate({ maxHeight: '1000px' }, 400)
          .addClass('accordion-opened');
        $(this).text('-');
    }
});     

这是原来的小提琴。

由于我是jQuery的新手,目前我对API了解不多。然而,我只是偶然发现了父方法。使用它,问题变得很容易,我的解决方案可以归结为:

trAcc.find('i').click(function () {
    if ($(this).parent('tr').hasClass('accordion-opened')) {
        $(this).parent('tr')
          .animate({ maxHeight: '50px' }, 200)
          .removeClass('accordion-opened');
        $(this).text('+');
    } else {
        $(this).parent('tr')
          .animate({ maxHeight: '1000px' }, 400)
          .addClass('accordion-opened');
        $(this).text('-');
    }
});              

我像这样修改了您原来的jsFiddle代码。

trAcc.append('<i class="icon-accordion">+</i>');
    $('.icon-accordion').on('click', function (e) {
        e.stopImmediatePropagation();
        if ($(this).parent().hasClass('accordion-opened')) {
            $(this)
                .parent()
                .animate({maxHeight: '60px'}, 200)
                .removeClass('accordion-opened')
                .end()
                .text('+');
        } else {
            $(this)
                .parent()
                .animate({maxHeight: '1000px'}, 400)
                .addClass('accordion-opened')
                .end()
                .text('-');
               }
       });