hashchange,一提hash前端GG、MM们都不稀奇,但是hashchange就鲜有人知了
在一次面试过程中面试官问道这么样实现ajax回退,这个问题当时闷了,下面附上具体代码,以备后用:
<div id="nihao"></div> <button>change</button>
var i=0,url; var show = function(num) { if (num == 0) { url = "data/data_1.json"; } else if (num == 1) { url = "data/data_2.json"; } $.get(url,{"cache":false},function(result) { $("#nihao").text(result.code); },"json"); }; if(window.attachEvent) { window.attachEvent("onhashchange",function(e) { var hash = parseInt(window.location.hash.substring(1,2),10); show(hash); }); } else if(window.addEventListener) { window.addEventListener("hashchange",10); show(hash); },false); } $("button").click(function() { if(i == 1) { window.location.hash = i--; } else if(i == 0) { window.location.hash = i++; } });
支持ie8+、chrome、firefox 原文链接:https://www.f2er.com/ajax/166406.html