我有一个表,如果我点击标题,我想折叠下一行。此外,无论表是否折叠,我都想更改类。
我写了这个:
$('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;
} 发布于 2014-09-05 10:00:05
您可以在多个类中使用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/
发布于 2014-09-05 09:57:08
$('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");
} 发布于 2014-09-05 09:55:29
脚本
$('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/
https://stackoverflow.com/questions/25683046
复制相似问题