问题描述
我有一个表格,默认情况下我只想显示第一行,但如果用户单击显示更多"链接,则显示额外的 X 行(如果用户然后单击,则相反地隐藏 X 行"显示更少").
I have a table for which I want to display only the first row by default, but display additional X number of rows if a user clicks a "show more" link (and inversely hide the X rows if the user then clicks "show less").
举例来说,我希望页面加载时的默认视图如下所示:
To exemplify, I want the default view when the page loads to be like so:
Top Scores
====================================
| 1 | show this row always! |
====================================
-show more-
然后,如果用户点击显示更多",表格应展开并显示更多行,如下所示:
Then, if a user clicks "show more", the table should expand with additional rows and look like this:
Top Scores
====================================
| 1 | show this row always! |
| 2 | newly displayed row |
| 3 | newly displayed row |
| 4 | newly displayed row |
| 5 | newly displayed row |
====================================
-show less-
然后很明显,如果用户点击显示更少",表格将返回默认值(再次仅显示第一行).
Then obviously if a user clicks "show less" the table returns to default (showing only the first row again).
我熟悉 jQuery 中的 .toggle()
函数,但不确定它是否可以在这里应用,或者我是否需要做更多的手动工作.
I'm familiar with the .toggle()
function in jQuery, but not sure if it can be applied here or if I have to do more manual work.
谢谢!
推荐答案
不需要额外的类,不需要标题 - http://jsfiddle.net/wgSZs/
No additional classes, no headers required - http://jsfiddle.net/wgSZs/
$('table').find('tr:gt(0)').hide();
$("button").on("click", function() {
$('table').find('tr:gt(0)').toggle();
});
更新
通过 CSS 而不是 jQuery 隐藏额外的行可能会更好,以避免在下载和应用 JS 时元素移动.但是仍然不需要添加类 - 保持标记尽可能干净是个好主意.你可以这样做:
It might be better to hide the additional rows via CSS instead of jQuery to avoid element shifting while the JS is being downloaded and applied. But still no need to add classes - it's a good idea to keep your markup as clean as possible. You can do this:
table tr { display: none }
table tr:first-child { display: block }
这是工作示例 - http://jsfiddle.net/wgSZs/1/
这篇关于切换其他表格行的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!