我有一个页面,我有多个数据表.
小提琴:
它<th>是一个<tr>带有类名的,每个行都有类似的命名...
rowToClick1 rowToClick2
......等等.
在for循环中,我动态生成数据 - 我有<tr>类名,类似于上面它们被命名为...
rowToExpand1 rowToExpand2
......等等.
目前,我的解决方案是扩展/折叠这些表,但它真的很难看:
$('.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+ ..
Run Code Online (Sandbox Code Playgroud)
我怎样才能更有效地做到这一点?
注意:我不希望表格同时展开/折叠,而是单独展开(就像我现在一样).
提前致谢.
我建议:
// 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();
});
Run Code Online (Sandbox Code Playgroud)
如果你只有一个 <tbody>元素,上面的工作; 如果你应该有多个元素,那么方法不起作用(由于使用next()); 如果有(可能)更多的<tbody>元素,那么你可以改为使用nextAll():
$('th').click(function () {
$(this).find('span').text(function (_, value) {
return value == '-' ? '+' : '-';
}).closest('thead').nextAll('tbody').find('tr').toggle();
});
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
2123 次 |
| 最近记录: |