2012-02-08 29 views
1

这样看起来好像是从变更中的URL获得#value的最佳方式,它确实有效,但只是想知道是否有更好的办法

$(function() { 
    $(window).bind('hashchange', function() { 
     var hash = window.location.hash; 
     var map = { 
      one: 1, 
      two: 2, 
      three: 3, 
      four: 4 
     }; 
     var hashValue = map[hash.substring(1)]; 
     alert(hashValue); 
    }); 
}); 
+0

这个问题可能更适合在http ://codereview.stackexcha nge.com? – 2012-02-08 11:44:05

+0

,它不会在较旧的IE浏览器工作,如果你喜欢迎合这些+新的浏览器可以使用pushState这是更好看看 – 2012-02-08 11:45:38

回答

0

您可以使用jquery.history插件:。http://tkyk.github.com/jquery-history-plugin/

它可以帮助你避免hashchange事件的一些跨浏览器的问题

function loadContent(hash) { 
    alert(hashValue); 
    // you can do some ajax here 
} 

$(document).ready(function() { 
    $.history.init(loadContent); 
});