我有一张桌子,如果点击标题,我想折叠下一行。此外,我想更改类,无论表是否折叠。
我写了这个:
$('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;
}
答案 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>
答案 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;
}