如何在我的代码中加入localStorage?我在谷歌地图上有一个隐藏和显示标记数组的显示和隐藏按钮。单击按钮时,我需要将值存储在localStorage中。
到目前为止我所拥有的:
var testbtn = document.getElementById('test1');
var testbtn2 = document.getElementById('test2');
google.maps.event.addDomListener(testbtn, 'click', hide);
google.maps.event.addDomListener(testbtn2, 'click', show);
function hide() {
set_speed_camera(null);
localStorage.setItem("hide_speed_camera", "true");
}
function show() {
set_speed_camera(map);
localStorage.setItem("show_speed_camera", "true");
}
$(document).ready(function(e) {
if(JSON.parse(localStorage.getItem("show_speed_camera"))) {
set_speed_camera(map);
alert('testing..Show')
}
});
$(document).ready(function(e) {
if(JSON.parse(localStorage.getItem("hide_speed_camera"))) {
set_speed_camera(null);
alert('testing..Hide')
localStorage.removeItem('hide_speed_camera');
}
});
答案 0 :(得分:0)
您有一个明显的问题,即您使用localStorage.getItem
来获取 stringified 布尔值。而是将JSON.parse
投射到getItem
:
var testbtn = document.getElementById('test1');
var testbtn2 = document.getElementById('test2');
google.maps.event.addDomListener(testbtn, 'click', hide);
google.maps.event.addDomListener(testbtn2, 'click', show);
function hide() {
set_speed_camera(null);
localStorage.setItem("hide_speed_camera", "true");
}
function show() {
set_speed_camera(map);
localStorage.setItem("show_speed_camera", "true");
}
if(JSON.parse(localStorage.getItem("show_speed_camera"))) {
set_speed_camera(map);
}
if(JSON.parse(localStorage.getItem("hide_speed_camera"))) {
set_speed_camera(null);
}
> Boolean("true")
true
> Boolean("false")
true
因此,除非您使用JSON.parse
,否则getItem
的结果将始终为true
。
答案 1 :(得分:0)
localStorage将所有内容存储为字符串。您需要检查当前设置的字符串形式。
if(localStorage.getItem("show_speed_camera") === "true") {
set_speed_camera(map);
}
if(localStorage.getItem("hide_speed_camera") === "true") {
set_speed_camera(null);
}
此外,您有两个字符串布尔控制相同的功能。也许不是同时将show_speed_camera
和hide_speed_camera
存储在localStorage中,只需要showing_speed_camera
,就像这样:
function hide() {
set_speed_camera(null);
localStorage.setItem("showing_speed_camera", "false");
}
function show() {
set_speed_camera(map);
localStorage.setItem("showing_speed_camera", "true");
}
if(localStorage.getItem("showing_speed_camera") === "true") {
set_speed_camera(map);
}
if(localStorage.getItem("hide_speed_camera") === "false") {
set_speed_camera(null);
}