返回上一页后Checkbox选中状态未触发Div显示的问题求助
问题描述
第一页有个checkbox,选中时会显示隐藏的div。但从第二页通过history.back()返回第一页后,checkbox保持选中状态,对应的div却被隐藏了。
相关代码
Checkbox代码
<div class="checkbox"> <label style='user-select: none'><input type="checkbox" name="chk" id="exceptions" value="1">Exceptions</label> </div>
目标div代码
<div class="panel panel-default" id="exceptionsPanel"> <div class="panel-heading">Available Exceptions</div> <div class="panel-body form-group"> <label for="exceptionsSelect">Exceptions:</label> <select name="exceptionsSelect" id="exceptionsSelect" class="selectpicker" data-width="20%" data-live-search="true" data-size="10" multiple data-actions-box="true" title="Select Exception" > </select> </div> </div>
初始处理函数
let exception = $('#exceptions'); $(function () { if (exception.prop('checked') == true) { $('#exceptionsPanel').show(); } else { $('#exceptionsPanel').hide(); } });
返回按钮代码
<div class="text-center"> <button type="button" class="btn btn-default" id="prevButton" onclick="history.back();" value="Back" >Prev </button> </div>
解决方案
问题根源是浏览器的**后退缓存(BF Cache)**机制:通过history.back()返回页面时,浏览器直接从缓存恢复页面,不会重新触发DOMContentLoaded(即$(function(){}))事件,导致初始化代码未执行,div保持默认隐藏状态。
以下是几种可行解决办法:
方法1:绑定pageshow事件覆盖缓存恢复场景
将状态同步逻辑绑定到pageshow事件,该事件在页面从缓存恢复时也会触发:
const $exception = $('#exceptions'); const $panel = $('#exceptionsPanel'); function togglePanel() { $panel.toggle($exception.prop('checked')); } // 页面首次加载/刷新时执行 $(togglePanel); // 从缓存恢复页面时执行 $(window).on('pageshow', togglePanel); // checkbox状态变更时同步更新 $exception.on('change', togglePanel);
方法2:精准监听缓存恢复事件
通过pageshow事件的persisted属性判断是否从缓存恢复,针对性执行状态同步:
$(function() { const $exception = $('#exceptions'); const $panel = $('#exceptionsPanel'); function updatePanel() { $panel.toggle($exception.prop('checked')); } // 初始加载时更新 updatePanel(); // checkbox变更时更新 $exception.on('change', updatePanel); // 从后退缓存恢复时更新 $(window).on('pageshow', function(e) { if (e.persisted) { updatePanel(); } }); });
方法3:禁用后退缓存(不推荐)
通过空的unload事件强制浏览器不缓存页面,但会导致页面每次后退都重新加载,影响性能:
$(window).on('unload', function() {});
内容的提问来源于stack exchange,提问作者AlExp
相关产品推荐
相关产品推荐

