我正在尝试使用Asual Address插件,以便我的后退按钮适用于 ajax 调用。我对这项工作的工作原理感到非常困惑,而且我发现的每个教程都说要暗示它不同。我无法让他们中的任何一个工作。
我有一个简单的 ajax 页面。它只是调用图像:
Javascript:
<script type="text/javascript">
$("a").live("click", function(event) {
url = $(this).attr("href");
$.address.value($(this).attr('href'));
event.preventDefault();
$.ajax({
type: "get",
url: "/"+url+".php",
data: "",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
},
})
});
</script>
我的 HTML 看起来像这样:
<body>
<a href="push1" onclick="return false;" >Image 1</a>
<a href="push2" onclick="return false;">Image 2</a>
<div id="Right_Content"></div>
</body>
使用上面的代码,当我单击一个链接时,它会进行 ajax 调用,加载图片并更改 url。这工作正常。我的问题是后退按钮。当我单击后退按钮时,网址会更改为上一个网址,但页面上的内容保持不变。我认为这与“popstate”有关,并将其添加到我的 js 中。我只是不知道该怎么做。
有人可以向我解释一下 popstate 是如何工作的,以及我如何将它添加到上面的代码中,以便我的后退按钮可以工作。谢谢你。
完整页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="/JS_Functions/jquery-ui-1.8.17.custom/js/jquery-1.7.1.min.js"></script>
<script src="/JS_Functions/jquery-ui-1.8.17.custom/js/jquery-ui-1.8.17.custom.min.js"></script>
<script src="JS_Functions/jquery.address-1.4/jquery.address-1.4.min.js"></script>
<script type="text/javascript">
$.address.init(function(event) {
// All elements with the "history" class will be "addressed". When they get clicked
// the href will get used as the new #part of the URL
$('a').address();
$('a').live("click", function(){
var href = $(this).attr( "href" );
$.ajax({
type: "get",
url: "/"+href+".php",
data: "",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
},
})
})
}).change(function(event) {
//Every time the url part changes this will be called.
// As an example here I determine the # part of the URL and default to 'home'
var hash = event.path.substring(1);
hash = hash? hash.toLowerCase(): 'push1';
//.. do the stuff here that you need to do when hash has a certain value
});
</script>
</head>
<body>
<a href="push1" >Image 1</a>
<a href="push2" >Image 2</a>
<div id="Right_Content"></div>
</body>
</html>