---
title: "ajax后退解决方案（五）"
author: "zhouyrt"
date: "2011-11-15T07:37:16Z"
tags: []
categories: ["Web前端"]
slug: "ajax"
draft: false
lastmod: "2011-11-15T07:37:16Z"
id: 1259009
url: "https://snandy.iteye.com/blog/1259009"
---

**五、使用history.pushState产生历史，popstate事件处理后退**

```
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>0</title>
</head>
<body>
	<input type="button" value="加1" onclick="add()" />
	<div id="info" style="border:red 1px solid;width:200px;padding:10px;">0</div>
</body>
</html>
<script src="history-0.5.js"></script>
<script>
	var info = document.getElementById('info');
	var i = 1;
	function add() {
		var data = {
		    param : i,
		    func : func
		};
		info.innerHTML = i;
		document.title = i;
		History.push(data);
		i++;
	}
	
	function func(i) {
	    info.innerHTML = i;
	    document.title = i;
	}
</script>
```

 

pushState和popstate是HTML5为history对象新增的方法和事件。虽然可以改变地址栏，但却不能复制地址栏的url直接进入该历史记录。该系列API知道IE10预览版尚不支持，Firefox/Safari/Chrome/Opera的最新版本均支持。

开发中应根据需求组合以上形式以兼容所有浏览器，如新浪微博就组合使用了方案一，四，五([base.js](http://js.t.sinajs.cn/t4/home/js/base.js))。如果项目中使用了一些开源库如jQuery，mootools等时强烈推荐使用[histroy.js](https://github.com/balupton/history.js) 。古老的dhtmlHistory.js和RSH已经很久没更新了。

 

[history-0.5.js](http://files.cnblogs.com/snandy/history-0.5.js)

相关：

[http://www.w3.org/TR/html5/history.html](http://www.w3.org/TR/html5/history.html)

[http://dev.opera.com/articles/view/introducing-the-html5-history-api/](http://dev.opera.com/articles/view/introducing-the-html5-history-api/)