总结:cookie的缺点很明显,最多只能存储4KB的数据,每个HTTP请求都会被传送回服务器,明文传输(除非你使用SSL)对于购物网站而言,
cookie是非常重要的,为了实现购物车功能,把已选物品加入cookie,可以实现不同页面之间数据的同步,同时在提交订单的时候又会把这些cookie传到后台,大大方便了前后端开.
SessionStorage和LocalStorage
SessionStorage当前页面会话存在,关闭当前回话,从新打开页面就不存在了。
localStorage,他是跨多个窗口,且持续范围可超过当前会话;意味着当浏览器关闭再重新打开,数据依然是可用的;拿上面的例子来说,当修改代码之后,在新的标签打开页面,仍然会弹出“yuanzm”.
参考:https://segmentfault.com/a/1190000002701423
参考:http://killtyz.com
$(document).ready(function () {
$('#add-input').focus();
$('#add-input').bind('keypress',function(event){
var value = $(this).val();
if( event.keyCode == "13" && value ) {
var time = (new Date()).getTime();
addItem(time, value, false);
store(time, value, false);
$(this).val('');
}
});
$('#list').click( function(event){
var target = $(event.target);
if (target.hasClass('delete')) {
target.parents('.list-group-item').remove();
localStorage.removeItem(target.parents('.list-group-item').attr('data-time'));
return false;
}
if (!target.hasClass('list-group-item')) {
target = $(target).parents('.list-group-item');
}
var check = target.children('.check').not('.checked');
if (check.length) {
changeStatus(target.attr('data-time'), true);
check.addClass('checked');
check.next('.value').addClass('checked');
check.next('.value').next('.delete').show();
} else{
changeStatus(target.attr('data-time'), false);
target.children('.check.checked').removeClass('checked');
target.children('.value.checked').removeClass('checked');
target.children('.delete').hide();
}
return false;
});
store(0, 'KillTYZ 基础 Todo-List 功能实现', true);
store(1, '浏览器本地存储 功能实现,请大胆刷新页面!', true);
for(x in localStorage) {
var obj = JSON.parse(localStorage.getItem(x));
addItem(obj.time, obj.value, obj.checked);
}
});
function store(time, value, checked) {
localStorage.setItem(time, stringify(time, value, checked));
}
function changeStatus(time, checked) {
var obj = JSON.parse(localStorage.getItem(time));
obj.checked = checked ? true : false;
localStorage.setItem(time, JSON.stringify(obj));
}
function stringify(time,value,checked) {
var obj = new Object;
obj.time = time;
obj.value = value;
obj.checked = checked;
return JSON.stringify(obj);
}
function addItem(time, value, checked) {
var node = checked ? '<a href="#" class="list-group-item" data-time="'+time+'"><span class="check checked"></span><span class="value checked">'+value+'</span><span class="delete glyphicon glyphicon-trash"></span></a>' : '<a href="#" class="list-group-item" data-time="'+time+'"><span class="check"></span><span class="value">'+value+'</span><span class="delete glyphicon glyphicon-trash" style="display: none;"></span></a>';
$('#list').prepend(node);
}