我有一个简单的表单,当在选择标记中选择类别时,它将显示隐藏的 div。
我想要的是当我刷新页面时,内容仍然可见,并且选中的项目仍然存在。
这里是示例代码
HTML
<select class="form-control" name="food_type1" id="food_type1">
<option selected="selected" disabled="disable" value="0">SELECT</option>
<option value="1">Fruits</option>
<option value="2">Meat</option>
</select>
<div id="food1" style="display: none;">
<input type="checkbox" name="food1[]" value="Mango">Mango <br>
<input type="checkbox" name="food1[]" value="strawberry">Strawberry
</div>
<div id="food2" style="display: none;">
<input type="checkbox" name="food2[]" value="Beef">Beef <br>
<input type="checkbox" name="food2[]" value="Pork">Pork <br>
<input type="checkbox" name="food2[]" value="Chicken">Chicken
</div>
脚本
$(document).ready(function(){
$('#food_type1').on('change', function() {
if ( this.value == '1') {
$("#food1").show();
$("#food2").hide();
}
else if ( this.value == '2') {
$("#food2").show();
$("#food1").hide();
} else {
$("#food1").hide();
$("#food2").hide();
}
});
});
fiddle
最佳答案
最简单的方法是使用本地存储。我已经更新了您的 fiddle ,但是您将无法在 JSFiddle 中测试刷新,因此您必须在您的计算机上本地尝试代码。
JSFiddle: https://jsfiddle.net/m0nk3y/bk2ohogj/4/
您必须创建几个函数来实现它。我使它们尽可能简单,因此它们可能无法解决您的所有用例,但这应该可以帮助您更接近您想要做的事情:
JS:
$(document).ready(function(){
var storedItems = [];
//Store selected items
function storeItem(item) {
storedItems.push(item);
localStorage.setItem("storage", storedItems);
}
//Remove item
function removeItem(item) {
var index = storedItems.indexOf(item);
storedItems.splice(index, 1);
}
//Show list according to Dropdown
function showList(type) {
var $food1 = $("#food1");
var $food2 = $("#food2");
localStorage.setItem("list", type);
if ( type == '1') {
$food1.show();
$food2.hide();
} else if ( type == '2') {
$food2.show();
$food1.hide();
} else {
$food1.hide();
$food2.hide();
}
}
//Get list type
if (localStorage.getItem("list")) {
showList(localStorage.getItem("list"));
}
//Get stored items
if (localStorage.getItem("storage")) {
storedItems = localStorage.getItem("storage");
$.each(storedItems, function(i, val) {
$('input[type="checkbox"][value="'+val+'"]').prop("checked", true);
});
}
//Dropdown
$('#food_type1').on('change', function() {
showList(this.value);
});
//Checkbox
$('input[type="checkbox"]').on('change', function() {
var $this = $(this);
if ($this.is(':checked')) {
storeItem(this.val())
} else {
removeItem(this.val());
}
});
});
关于javascript - 隐藏的div在刷新时仍然可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733936/