如何在页面重新加载后保持复选框切换div的状态? [英] How do you maintain the state of a checkbox-toggled div after page reload?
本文介绍了如何在页面重新加载后保持复选框切换div的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我选中了一个复选框时出现div,并在取消选中时隐藏。如果表单有错误,页面会重新加载,即使在提交前选中了复选框,div也会显示为隐藏状态。我可以添加对onLoad事件的调用,但有没有更清晰的方法来确保在页面重新加载后,div是根据复选框的状态呈现的?
I have a div that appears when a checkbox is checked, and hides when unchecked. If the form has errors, the page reloads and the div appears hidden even if the checkbox was checked before submission. I can add a call to the onLoad event, but is there a cleaner way to ensure that, after page reload, the div is rendered based on the status of the checkbox?
Css:
#maintenance-window { display: none; }
jQuery:
$("#check-hasMaintenance").click(function() {
$(this).is(":checked") ? $('#maintenance-window').show("fast") : $('#maintenance-window').hide("fast")
});
HTML:
<input type="checkbox" value="1" id="check-hasMaintenance">
<div id="maintenance-window">
Stuff
</div>
推荐答案
选项1
当页面加载时,确保基于复选框显示div:
Ensure div is shown based on check box when the page loads:
$(document).ready(function() {
// Modified for readability - inline if is fine.
if($("#check-hasMaintenance").is(":checked"))
$('#maintenance-window').show("fast")
else
$('#maintenance-window').hide("fast");
});
简化隐藏/显示代码:
$("#check-hasMaintenance").click(function() {
$('#maintenance-window').toggle('fast');
});
选项2
像这样的简写版也应该有效:
A short-hand version like this should work as well:
$(document).ready(function() {
$('#maintenance-window').toggle($("#check-hasMaintenance").is(":checked"));
});
$("#check-hasMaintenance").click(function() {
$('#maintenance-window').toggle('fast');
});
这篇关于如何在页面重新加载后保持复选框切换div的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文