当页面重新加载时,Jquery显示/隐藏重置 [英] Jquery show/hide resetting when page reloads
问题描述
我是jquery的新手,但我正在尝试使用它创建一个多步骤的标签形式。
I'm new to jquery, but I'm trying to use it to create a multi-step tabbed form.
其中一个页面,我有单选按钮将根据所选的选项显示多个字段。
One one of the pages, I have radio buttons that will show several fields depending on the choice that's selected.
我发现的问题是,如果用户在选择单选按钮后刷新页面,页面将重新加载并隐藏所有div,但它会记住选中的单选按钮选项。
The problem I find is that if the user refreshes the page after selecting a radio button, the page reloads and hides all the divs, but it remembers the selected radio button choice.
有没有办法在页面加载后没有明确告诉它发生时最初隐藏div?或许有一些(简单)让jquery记住div隐藏的内容和显示的内容?
Is there a way to initially hide the divs without explicitly telling it to happen after a page loads? Perhaps some (easy) way of having jquery remember what div is hidden and which is shown?
谢谢!
<label for="paymentmethod">Payment Method</label>
<input type="radio" name="paymentmethod" id="paymentmethod" value="creditcard">Visa/Mastercard
<input type="radio" name="paymentmethod" id="paymentmethod" value="cheque">Cheque
<div id="divcredit">
Stuff
</div>
<div id="divcheque">
Stuff
</div>
这是我的jquery代码:
Here's the jquery code I have:
$(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);
});
并添加 class =payment
到div。这会滥用后退按钮和刷新记住表单值的事实。
and add class="payment"
to the divs. This abuses the fact that the back button and refresh remember the form values.
另一种方法是将当前状态编码到某个地方 - 在cookie中,在URL哈希中。然后在加载时提取它并相应地设置所有值。优点是即使您关闭浏览器也能正常工作,即使您将URL粘贴到朋友的浏览器,也会出现URL哈希。 (好吧,也许不适用于支付系统:D,但你知道我的意思)
Another way is to encode the current state somewhere - in a cookie, in a URL hash... and then extract it on load and set all the values accordingly. Advantage is that it works even if you shut down the browser, and in the case of URL hashes, even if you paste the URL to your friend's browser. (Well, maybe not for payment system :D but you know what I mean)
这篇关于当页面重新加载时,Jquery显示/隐藏重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!