js localStorage jsonオブジェクトをローカルに格納し、データを追加
2085 ワード
localStorageのもっと関連する知識を記録してください.http://www.w3school.com.cn/html5/html_5_webstorage.aspここでは主にlocalStorageがオブジェクトを格納する際に追加データが元のデータを上書きしないことを説明し、以下に小さなdemoを書きます
効果図は以下の
:
:
:
// localStorage.removeItem('data'); //
var jsonData = JSON.parse(localStorage.getItem('data'));
console.log(jsonData);
if(!jsonData){
jsonData = [];
}
else{
//
show();
}
function btn(){
if(!$(".name").val() || !$(".age").val() || !$(".sex").val()){
alert(" ");
}
else{
jsonData.push({
name:$(".name").val(),
age:$(".age").val(),
sex:$(".sex").val()
});
console.log(jsonData);
$(".name").val("");
$(".age").val("");
$(".sex").val("");
localStorage.setItem('data',JSON.stringify(jsonData));
$(".tt").empty();
show();
}
}
// DOM
function show(){
for(key in jsonData){
$(".tt").append(`
<tr>
<td>${jsonData[key].name}</td>
<td>${jsonData[key].age}</td>
<td>${jsonData[key].sex}</td>
</tr>
`);
}
}
効果図は以下の