location.hash来保持页面状态

 /*本例是为了在客户端页面返回时保存状态,采用hash值记录的模式,为了使用方便所写的存取hash值的库,时间仓促,望指出错误。*/
var
pageStateHash = { hashArray: [], getHashArray: function() { var _self = this; if (window.location.hash.replace('#','') != '') { _self.hashArray = window.location.hash.replace('#','').split('&'); } }, applyHash: function() { var _self = this; window.location.hash = '#' + _self.hashArray.join('&'); }, hashIndex: function(key) { var _self = this; var ret = -1; _self.getHashArray(); for (var i in _self.hashArray) { var item = _self.hashArray[i].split('='); var length = item.length; if (length == 2 && item[0] == key) { ret = i; } } return ret; }, set: function(key, value) { var _self = this; var hashIndex = _self.hashIndex(key); console.log('hash index = '+hashIndex); if (hashIndex == -1) { _self.hashArray.push(key + '=' + value); } else { _self.hashArray[hashIndex] = key + '=' + value; } _self.applyHash(); }, get: function(key) { var _self = this; var hashIndex = _self.hashIndex(key); if (hashIndex == -1) { return ''; } else if (_self.hashArray[hashIndex].split('=').length == 2) { return _self.hashArray[hashIndex].split('=')[1]; } } }; /*pageStateHash.set('cate1', '8'); pageStateHash.set('cate2', '9'); console.log('get cate2 index:' +pageStateHash.get('cate2'));*/

 

posted @ 2015-09-24 18:33  冰狐2009  阅读(1006)  评论(0编辑  收藏  举报