使用更优雅的解决方案展开/折叠多个表行
我有一个页面,我有多个数据表。
小提琴:
DEMO
,每个行都有类似的命名…
rowToClick1
rowToClick2
……等等。
在for循环中,我动态生成数据 – 我有
的类名,类似于上面它们被命名为…
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+ ..
我怎样才能更有效地做到这一点?
注意:我不希望表格同时展开/折叠,而是单独展开(就像我现在这样)。
提前致谢。
我建议:
// 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(); });
JS小提琴演示 。
如果你只有一个
元素,上面的工作; 如果你应该有多个元素,那么方法不起作用 (由于使用了next()
); 如果有(可能)更多的
元素,那么你可以改为使用nextAll()
:
$('th').click(function () { $(this).find('span').text(function (_, value) { return value == '-' ? '+' : '-'; }).closest('thead').nextAll('tbody').find('tr').toggle(); });
JS小提琴演示 。
参考文献:
-
click()
。
-
closest()
。
-
find()
。
-
next()
。
-
nextAll()
。
-
toggle()
。
看看这个…
$('tr[class^="rowToClick"]').click(function () { // remove all non-numbers from the class with regex theNumber = $(this).attr('class').replace(/\D/g,''); // append the variable to the class name $(".rowToExpand"+theNumber).toggle(); });
看一下文档:
tr[class^="rowToClick"]
: http : tr[class^="rowToClick"]
$('tr[class^="rowToClick"]').click(function () { $(this).find('span').text(function (_, value) { return value == '-' ? '+' : '-'; }); var className = $(this).attr("class"); var id = className.replace("rowToClick",""); $(".rowToExpand"+id).toggle(); });