javascript/ajax浏览器历史记录后退解决方案I

  使用iframe,通过document.write产生浏览器历史

 

示例代码

<!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;margin:5px;">0</div>
</body>
</html>
<script>
/**
 * history.js v0.1
 * Copyright (c) 2011 snandy
 * 
 * 1 使用iframe,通过document.write产生历史
 * 2 IE6/7/8/9/10/Firefox支持,Safari/Chrome/Opera不支持
 * 
 * example:
 * 
 * History.push({
 *     param : // func参数
 *     func : 回调函数
 *     scope : func执行上下文
 * });
 */
History = function() {
	
	var 
	   iframe,
	   
	   // 存储历史记录
	   list = [],
	   
	   // 历史记录索引
	   index = 0,
	   
	   pushing;
	
    iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.onload = function() {
        var doc = iframe.contentWindow.document,
            el  = doc.getElementById('idx');
        
        if(pushing) return;
        
        if(el) {
            idx = el.innerHTML;
            get(idx);
        }
        else { // el为null
            get('0');
        }
        
        
    }
    document.body.appendChild(iframe);
    
	function push(data) {
	    if(typeof data !== 'object') return;
	    
	    if(typeof data.param == undefined || typeof data.func !== 'function') return;
	    
		list[index] = data;
		updateIframe();
		pushing = true;
		index++;
		
		setTimeout(function(){
		    pushing = false;
		}, 1000);
	}
	
	function updateIframe() {
        var doc = iframe.contentWindow.document;
        try{
            doc.open();
            doc.write('<div id="idx">' + index + '</div>');
            doc.close();
        }catch(e){
            
        }
	}
	
	function get(idx) {
	    var item, param, func, scope;
		if(idx != index) {
		    item = list[idx];
			if(item) {
                param = item.param;
                func  = item.func;
                scope = item.scope;
                func.call(scope, param);
			}
		}
		
	}
	
	return {
		push : push
	};
}();
</script>
<script>
    var info = document.getElementById('info');
    var i = 1;
    function add() {
        info.innerHTML = i;
        document.title = i;
        var data = {
            param : i,
            func : func
        };
        History.push(data);
        i++;
    }
     
    History.push({param:0, func: func});
     
    function func(i) {
        info.innerHTML = i;
        document.title = i;
    }
</script>

  点击按钮后更新页面DOM(模拟ajax提交),会发现浏览器后退按钮可用了。点击后退,可返回到前一个状态。

这种方式缺点是只支持IE和Firefox。

来源:http://www.cnblogs.com/snandy/archive/2011/09/18/2180102.html

 

加支付宝好友偷能量挖...


评论(0)网络
阅读(118)喜欢(0)JavaScript/Ajax开发技巧