Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/84e4e5da30e53e1272a3 to your computer and use it in GitHub Desktop.
Save Cartman0/84e4e5da30e53e1272a3 to your computer and use it in GitHub Desktop.
#ハッシュにより、Ajaxでロードするページの切り替え(アンカーリンクのAjax版)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>changeLoadedPageAjaxForHash_sample</title>
<link rel="stylesheet" href="http://fonts.googleapis.com/earlyaccess/notosansjapanese.css">
<style>
html, body{
font-family: 'Noto Sans Japanese', sans-serif;
width: 100%;
}
.menu {
display: block;
width: 100%;
}
.menu-l, .menu-l a {
display: inline-block;
width: 30%;
}
.wrapper {
border: 1px solid #333;
border-radius: 0.5rem;
margin: 1rem;
padding: 1rem;
}
</style>
</head>
<body>
<h1>Sample, change ajax loaded page follow hash</h1>
<ul class="menu">
<li class="menu-l"><a href="#?hash1">#?hash1</a></li>
<li class="menu-l"><a href="#?hash2">#?hash2</a></li>
<li class="menu-l"><a href="#?hash3">#?hash3</a></li>
</ul>
<div class="wrapper">
</div>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function(){
(function() {
var hashs = ['#?hash1', '#?hash2', '#?hash3'];
var toLoadHtml = 'html/' + hashs[0].replace(/#\?/g, '') + '.html';
//通常
var hash = window.location.hash;
changeAjaxPageforHash(hash, hashs);
// hashChange
window.onhashchange = function(){
hash = window.location.hash;
changeAjaxPageforHash(hash, hashs);
};
//click時
$('.menu .menu-l').click(function(e){
hash = $(this).children('a').attr('href');
changeAjaxPageforHash(hash, hashs);
});
function changeAjaxPageforHash(hash, hashs){
if(hash){
// console.log(hash);
for ( i_hash of hashs) {
if(hash === i_hash){
toLoadHtml = 'html/' + hash.replace(/#\?/g, '') + '.html';
}
}
}
$.ajax({
url: toLoadHtml,
dataType: 'html',
// chache: true
})
.done(function(data) {
console.log("success");
$('.wrapper').html(data);
})
.fail(function() {
console.log("error");
$('.wrapper').html(
'<p>Error, not Found File.</p>'
)
.css('color', red);
})
}
})();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment