Skip to content

Instantly share code, notes, and snippets.

@nimezhu
Last active September 21, 2015 03:20
Show Gist options
  • Save nimezhu/364fc2facd8e52065a7c to your computer and use it in GitHub Desktop.
Save nimezhu/364fc2facd8e52065a7c to your computer and use it in GitHub Desktop.
LocalStorage Save Map Example
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
<input type="text" id="in"></input>
<button id="add" value="add" >add</button>
<button id="clear" value="clear" >clear</button>
<button id="load" value="load" >load</button>
<button id="save" value="save" >save</button><span id="buffer"></span>
</div>
<div id="list">
</div>
<script>
$(function($){
var add = function() {
var x=$("#in").val()
if (zmap[x])
{
zmap[x]=zmap[x]+1;
}
else
{
zmap[x]=1;
}
$("#buffer").html("*")
show()
}
var del = function() {
}
var show= function() {
var s="<ul>"
Object.keys(zmap).forEach( function(d) {
s+="<li>"+d+" "+zmap[d]+"<button id='DEL_"+d+"' class='DEL'>del</button></li>"
})
s+="</ul>"
$("#list").html(s);
$(".DEL").on("click",function(d) {
console.log($(this).attr("id").replace("DEL_",""))
var id=$(this).attr("id").replace("DEL_","")
zmap[id]=zmap[id]-1;
if(zmap[id]==0) {delete zmap[id]}
$("#buffer").html("*")
show();
})
}
var clear=function() {
zmap={};
$("#buffer").html("*")
show();
}
if(localStorage.zmap==undefined) { localStorage.zmap="{}"}
var zmap;
var load=function() {
zmap=JSON.parse(localStorage.zmap);
show();
}
load()
$("#add").on("click",function(d) {console.log("add");add()})
$("#load").on("click",function(d) {load();$("#buffer").html("loaded")})
$("#clear").on("click",function(d) {clear()})
$("#save").on("click",function(d) {localStorage.zmap=JSON.stringify(zmap);$("#buffer").html("saved")})
}(jQuery))
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment