基于日期隐藏表格行并添加切换显示按钮的技术实现求助
实现历史日期行的切换显示功能
当然可以实现这个功能!其实只需要在你现有代码基础上做几个小调整就能搞定,我来一步步给你说清楚:
核心思路
- 给需要切换的历史日期行标记一个专属类(比如
past-event),方便后续统一控制 - 给切换按钮绑定专属事件,点击时切换这些标记类的行的显示状态
- 同步更新按钮文字,让用户清楚当前的操作状态
修改后的完整代码
HTML部分(调整按钮和表格)
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> /* 用CSS控制历史行的默认隐藏,比直接用JS设置更规范 */ .past-event { display: none; } </style> </head> <body> <p>This is a paragraph which can be hidden by clicking the button.</p> <!-- 给按钮加ID,方便JS精准选择,同时修改默认文字 --> <button id="toggle-history-btn">显示历史事件</button> <p>This table below shows only event dates in the future. Which is what I want. But I also want to have a toggle button option which does show the previous events. Is this possible?</p> <div class="table-responsive"> <table class="event_display_table" border="1" > <thead> <tr> <th>Date</th> <th>Event</th> </tr> </thead> <tbody data-date="2018-03-13"> <tr> <td>2018-03-13</td> <td>My event detail 1</td> </tr> <tr> <td>2018-05-14</td> <td>My event detail 2</td> </tr> </tbody> <tbody data-date="2018-05-13"> <tr> <td>2018-05-13</td> <td>My event detail 3</td> </tr> </tbody> <tbody data-date="2018-05-15"> <tr> <td>2018-05-15</td> <td>My event detail 4</td> </tr> <tr> <td>2018-06-27</td> <td>My event detail 5</td> </tr> </tbody> <tbody data-date="2018-06-15"> <tr> <td>2018-06-15</td> <td>My event detail 6</td> </tr> </tbody> </table> </div> </body>
JavaScript部分(优化逻辑并添加切换功能)
$(document).ready(function(){ // 处理段落的折叠(保留你原来的功能) $("button:not(#toggle-history-btn)").click(function(){ $("p").slideToggle(); }); // 初始化:标记并隐藏历史事件行 $('.event_display_table tbody').each(function(index, element) { const eventDay = new Date($(this).attr('data-date')); const today = new Date(); // 注意:这里把今天的时间重置为0点,避免当天的事件被误隐藏 today.setHours(0, 0, 0, 0); if(eventDay.getTime() < today.getTime()) { $(this).addClass('past-event'); } }); // 绑定历史事件切换按钮的点击事件 $('#toggle-history-btn').click(function() { // 切换所有历史行的显示状态 $('.past-event').slideToggle(); // 更新按钮文字 const currentText = $(this).text(); $(this).text(currentText === '显示历史事件' ? '隐藏历史事件' : '显示历史事件'); }); });
关键调整说明
- 添加CSS类控制隐藏:用
.past-event类来标记历史行,通过CSS默认隐藏,比直接用JS修改display属性更易维护 - 优化日期比较逻辑:把
today的时间重置为0点,避免当天的事件因为当前时间晚于事件日期的0点而被误隐藏(比如今天是2018-05-13,现在是下午3点,事件日期是2018-05-13,不会被当成历史事件) - 专属按钮选择器:给切换按钮加了
id="toggle-history-btn",避免和其他按钮的事件冲突 - 动态按钮文字:点击按钮时切换文字,让用户清晰知道当前操作对应的状态
这样调整后,页面加载时会默认隐藏历史事件行,点击按钮可以切换显示/隐藏,完全满足你的需求~
内容的提问来源于stack exchange,提问作者StackPhrake
相关产品推荐
相关产品推荐

