当页面重新加载时,Jquery显示/隐藏重置

我是jquery的新手,但我正在尝试用它来创建一个多步骤的选项卡表单。

其中一个页面,我有单选按钮,根据所选的选项显示几个字段。

我发现的问题是,如果用户在选择单选按钮后刷新页面,页面将重新加载并隐藏所有div,但它会记住所选的单选按钮选项。

有没有办法最初隐藏div而不明确告诉它在页面加载后发生? 也许有一些(简单的)让jquery记住div被隐藏的东西以及显示的东西?

谢谢!

 Visa/Mastercard Cheque 
Stuff
Stuff

这是我的jquery代码:

 $(document).ready(function() { //...stuff $("#divcredit").hide(); $("#divcheque").hide(); $("input[name='paymentmethod']").change(function() { if( $("input[name='paymentmethod']:checked").val() == "cheque") { $("#divcredit").hide(); $("#divcheque").show(); } else if($("input[name='paymentmethod']:checked").val()== "creditcard") { $("#divcredit").show(); $("#divcheque").hide(); } }); 

 var setPaymentDivs = function() { var selected = $('input[name="paymentmethod"]:checked').val(); $('div.payment').hide(); $('#div' + selected).show(); }; $(function() { setPaymentDivs(); $('input[name="paymentmethod"]').change(setPaymentDivs); }); 

并将div class="payment"添加到div。 这会滥用后退按钮和刷新记住表单值的事实。

另一种方法是将当前状态编码在某个地方 – 在cookie中,在URL哈希中…然后在加载时提取它并相应地设置所有值。 优点是即使您关闭浏览器也能正常工作,即使您将URL粘贴到朋友的浏览器,也会出现URL哈希。 (好吧,也许不适用于支付系统:D但你知道我的意思)

Cookies是你的朋友。

http://www.quirksmode.org/js/cookies.html

– 或者,带有jQuery插件 –

http://plugins.jquery.com/cookie

或者,localStorage是你的朋友!

 $(document).ready(function() { //...stuff if (localStorage['payment']) { if (localStorage['payment'] === 'credit') $("#divcheque").hide(); else $("#divcredit").hide(); } else { $("#divcheque").hide(); $("#divcredit").hide(); } $("input[name='paymentmethod']").change(function() { if( $("input[name='paymentmethod']:checked").val() == "cheque") { $("#divcredit").hide(); $("#divcheque").show(); localStorage['payment'] = 'cheque'; } else if($("input[name='paymentmethod']:checked").val()== "creditcard") { $("#divcredit").show(); $("#divcheque").hide(); localStorage['payment'] = 'credit'; } }); 

http://diveintohtml5.ep.io/storage.html

要获得跨浏览器兼容性,请使用Cookie。 但无论从哪种方式来看,即使您的用户离开一段时间,它也会起作用; 你可能想要或不想要的东西。

配置更改事件后尝试。

 if( $("input[name='paymentmethod']:checked").length > 0){ $("input[name='paymentmethod']").change(); } 

这意味着在加载页面后,检查是否选择了一个选项并触发事件以获得所需的行为

你可能想要的是使用(一个) jQuery历史插件 。 这将允许浏览器根据哈希值返回显示所需的div。

但是,如果您在刷新时依赖页面保持已选中/未选中的值,则只有在为其添加代码时才能正常工作。 IE浏览器。 并非所有浏览器都在页面刷新时保留表单值,除非已明确设置页面以执行此操作。 这很可能意味着通过ajax发布数据,将信息存储在会话中并让页面在输出时考虑该信息。

通过提取一个方法稍微修改你的jquery:

  $(document).ready(function() { //...stuff ShowHidePanels(); $("input[name='paymentmethod']").change(function() { ShowHidePanels(); }); function ShowHidePanels(){ if( $("input[name='paymentmethod']:checked").val() == "cheque") { $("#divcredit").hide(); $("#divcheque").show(); } else if($("input[name='paymentmethod']:checked").val()== "creditcard") { $("#divcredit").show(); $("#divcheque").hide(); } }; }); 

哇我很慢,无论如何,这是我的解决方案:
http://jsfiddle.net/FerMU/

此外,您还会对复选框上的标签和ID感到困惑。