slideToggle with classToggle

时间:2014-09-05 09:48:26

标签: javascript jquery html collapse

我有一张桌子,如果点击标题,我想折叠下一行。此外,我想更改类,无论表是否折叠。

我写了这个:

$('th').click(function(){
        var $el = $(this)
        $(this).closest('tr').next().slideToggle(0)
        if($(this).closest('tr').next().is(':visible')) {
           $el.addClass   ('opened');
           $el.removeClass('closed');
        } else {
           $el.removeClass   ('opened');
           $el.addClass      ('closed');
        }
});  

我想知道我是否可以用JQuery做得更好?

这是HTML代码:

<table>
    <tr>
        <th colspan="2">Line 1</th>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
    </tr>
    <tr>
        <th colspan="2">Line 2</th>
    </tr>
    <tr>
        <td>date</td>
        <td>data</td>
    </tr>
</table>  

和css:

.opened {
    background-image: url("bullet_toggle_minus.png");
    background-repeat: no-repeat;
    background-position: left center;
}

.closed {
    background-image: url("bullet_toggle_plus.png");
    background-repeat: no-repeat;
    background-position: left center;
}  

3 个答案:

答案 0 :(得分:3)

您可以将toggleClass用于多个类:

$('th').click(function () {
    var $el = $(this)
    $el.closest('tr').next().slideToggle(0);
    $el.toggleClass('opened closed');
});

请记住通过在th上设置类来设置所有元素的初始状态:

<th colspan="2" class="opened">Line 1</th>

演示:http://jsfiddle.net/r0xpbqea/

答案 1 :(得分:0)

$('tr').addClass('opened');
$('th').click(function(){
        var $el = $(this)
        $(this).closest('tr').next().slideToggle(0).toggleClass('opened closed');
}); 

CSS

tr {
    background-repeat: no-repeat;
    background-position: left center;
}

.opened {
    background-image: url("bullet_toggle_minus.png");
}

.closed {
    background-image: url("bullet_toggle_plus.png");
} 

答案 2 :(得分:-1)

<强>脚本

$('th').click(function() {
        var $el = $(this);
        $(this).closest('tr')
               .next()
               .slideToggle(0)
               .toggleClass('closed');
});  

<强>风格

tr {
    background-image: url("bullet_toggle_minus.png");
    background-repeat: no-repeat;
    background-position: left center;
}

tr.closed {
    background-image: url("bullet_toggle_plus.png");
    background-repeat: no-repeat;
    background-position: left center;
} 

小提琴:http://jsfiddle.net/teh94dma/