在页面http://carmen-rails-demo.herokuapp.com/中,有一个关于国家/州选择的示例,这种选择在网络表单中非常常见。
我们假设您选择了美国和科罗拉多州,然后您点击了F5。在这种情况下,国家代码将被记住,但不会记住状态代码,因为它加载了ajax。
如何在使用F5页面刷新后保存此状态并恢复它?
答案 0 :(得分:1)
您可以使用localStorage保存国家/地区和代码,如下所示:
$('.country').change(function() {
var country = $(this).val();
localStorage.setItem('country', country);
$.get('states', {country: country}, function(data) {
localStorage.setItem('states', JSON.stringify(data));
var $states = $('.states');
data.forEach(function(state) {
$states.append('<option value="'+state.value+'">' +
state.value + '</option>');
});
});
});
$('.states').change(function() {
localStorage.setItem('state', $(this).val());
});
var country = localStorage.getItem('country');
if (country) {
$('.country').val(country);
}
var states = localStorage.getItem('states');
if (states) {
states = JSON.parse(states);
var $states = $('.states');
states.forEach(function(state) {
$states.append('<option value="'+state.value+'">' +
state.value + '</option>');
});
var state = localStorage.getItem('state');
if (state) {
$states.val(state);
}
}