Created
October 13, 2013 05:22
-
-
Save 59naga/6958463 to your computer and use it in GitHub Desktop.
history APIについて ref: http://qiita.com/59naga/items/9fca0248f0bfd5e9c089
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.addEventListener('popstate',function(){console.log(location.search)}); | |
history.pushState(null,null,'?page=2'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<meta charset="UTF-8"> | |
<script> | |
window.addEventListener('load',main,false); | |
function main(){ | |
var _title=document.title; | |
var buttons=document.querySelectorAll('button'); | |
Array.prototype.forEach.call(buttons,function(button){ | |
button.onclick=function(){ | |
var query=Query.create(location.search); | |
query.button=this.innerText; | |
history.pushState(null,null,query.toString()); | |
window.dispatchEvent(document.createEvent('PopStateEvent')); | |
} | |
}); | |
window.addEventListener('popstate',function(event){ | |
var title=_title; | |
var query=Query.create(location.search); | |
if(query.hasOwnProperty('button')){ | |
title=query.button; | |
} | |
switch(query.button){ | |
case 'hoge': | |
document.querySelector('pre').innerText=1; | |
break; | |
case 'fuga': | |
document.querySelector('pre').innerText=2; | |
break; | |
case 'piyo': | |
document.querySelector('pre').innerText=3; | |
break; | |
default: | |
document.querySelector('pre').innerText=0; | |
break; | |
} | |
document.title=title;//pushStateに適用される | |
},false); | |
} | |
Query.create=function(search){return new Query(search)} | |
function Query(search){ | |
var self=this; | |
Object.call(self); | |
var search=search? search.substr(1): ""; | |
if(search){ | |
search.split('&').forEach(function(param){ | |
var param=param.split('='); | |
var key=decodeURIComponent(param[0]); | |
var value=param[1]; | |
if(value){ | |
value=decodeURIComponent(param[1]); | |
} | |
self[key]=value; | |
}); | |
} | |
} | |
Query.prototype.toString=function(){ | |
var params=[]; | |
for(var key in this){ | |
if(this.hasOwnProperty(key)){ | |
var param=encodeURIComponent(key); | |
if(this[key]){ | |
param+='='+encodeURIComponent(this[key]); | |
} | |
params.push(param); | |
} | |
} | |
return params.length? "?"+params.join('&'): ""; | |
} | |
</script> | |
<body> | |
<button>hoge</button> | |
<button>fuga</button> | |
<button>piyo</button> | |
<pre></pre> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment