在本地存储中存储复选框值 [英] Storing checkbox value in local storage
问题描述
我有一个复选框,其值$row['uid']
我想使用javascript或jquery存储在本地存储中.当用户取消选中"复选框时,应从本地存储中删除该值
I have a checkbox whose value $row['uid']
I would like to store in local storage using javascript or jquery. When the user "unchecks" the checkbox, the value should be removed from local storage
这是我的html:
<form> Favorites <input type="checkbox" class="favorite" value="'.$row['uid'].' onclick='.fave.add();'"></form>
这是我目前用于javascript的本地存储的内容.我不太确定如何添加和删除值$row['uid']
This is what I have for the local storage in javascript at the moment. I'm not quite sure how I should add and remove the value $row['uid']
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
var fave = fave || {};
var data = JSON.parse(localStorage.getItem("favorite"));
data = data || {};
$(function () {
var data = localStorage.getItem("favorite");
if (data !== null) {
$("input[name='favorites']").attr("checked", "checked");
}
});
$("input[name='favorites']").click(function () {
if ($(this).is(":checked")) {
localStorage.setItem("favorite", $(this).val());
}
else {
localStorage.removeItem("favorite");
}
});
任何帮助都将不胜感激!
Any and all help is much appreciated!
推荐答案
localStorage
具有两个主要功能,getItem
和setItem
.对于setItem
,您传入一个键和一个值.如果再次写入该键,它将重写该值.因此,在您的情况下,如果选中一个框,您将执行localStorage.setItem("checkbox_value", true)
,而未选中该框时,您将传递false
.要获取值,您可以像这样使用jQuery:$(checkbox).is(':checked')
并使用简单的if-else子句传递true或false.然后,当您重新加载页面时,可以在$( document ).ready()
上使用localStorage.getItem(key)
获取值,并使用Javascript设置复选框值.
localStorage
has two main functions, getItem
and setItem
. For setItem
you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do localStorage.setItem("checkbox_value", true)
and when it is unchecked you would pass in false
instead. To get the value you can look at using jQuery like so: $(checkbox).is(':checked')
and use a simple if-else clause to pass in true or false. then when you reload your page, on $( document ).ready()
you can get the values using localStorage.getItem(key)
and use Javascript to set the check boxes values.
这就是我使用localStorage记住复选框值的方式.
This is how i would go about using localStorage to remember check box values.
希望我能帮上忙!问我是否不清楚.
Hope i helped! Ask me if anything is unclear.
这篇关于在本地存储中存储复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!