我使用AJAX加载内容,并使用pushastate更改URL,下面是我的代码,任何人都可以告诉我如何在我的情况下实现onpopstate启用后退按钮。
HTML
<div id="tabs" style="margin:1px 0px 0px 15px;">
<ul class="tabs-ul">
<li id="boardLi" class="current-tab"><a class="current-tab" href="board.jsp">Board</a></li>
<li id="aboutLi"><a href="aboutme.jsp">Info</a></li>
<li id="photoLi"><a href="photo.jsp">Photo Albums</a></li>
</ul>
</div>
JS
$(document).ready(function() {
function loadContent(path,c,pageName){
$.ajax({ url: path, success: function(html) {
$('#ajax-content').empty().append(html);
window.history.pushState({path:''},'',pageName+'?tab='+c);
}
});
}
function checkC(target){
var c='';
if(target=='aboutme.jsp')
{c='info';}
else if(target=='board.jsp')
{c='board';}
else if(target=='photo.jsp')
{c='photo';}
else if(target=='tab.jsp')
{c='ht';}
return c;
}
$(".tabs-ul li a").on('click', function(e) {
e.preventDefault();
$('#ajax-content').empty().append("<div id='loading'><img src='images/preloader.gif' alt='Loading' /></div>");
$('.tabs-ul li a').removeClass('current-tab');
$('.tabs-ul li').removeClass('current-tab');
$(this).addClass('current-tab');
$(this).parent().addClass('current-tab');
var url = window.location.pathname;
var pageName = url.substring(url.lastIndexOf('/') + 1);
var target=$(this).attr('href');
var c=checkC(target);
loadContent(target,c,pageName);
return false;
});
var loaded = false;
window.onpopstate = function(e) {
if (!loaded) {
loaded = true;
return;
} else {
alert(window.loacation.back().pathname);
loadContent();
}
};
});
当用户点击链接时,首先我要添加删除类进行加载然后我获取URL并从该URL获取页面名称(保存在'pageName'中),'target'是点击链接的href attr和'c'是我将在url中显示的值(例如,example.com/profile.jsp?tab = info,如果href是info.jsp,那么'c'将是info),最后我打电话给' loadContent'函数,它使用pushState加载ajax内容并更改URL。