2012-04-30 38 views

回答

5
// example.com/#login 
if (window.location.hash) { 
    alert("URL has hash"); 
    var hash = window.location.hash; // = "#login" 
    callMyFunction(); 
} 
1

如果你想要處理的URL是一個很好的跨瀏覽器庫,我會考慮History.js

https://github.com/browserstate/History.js/

History.Adapter.bind(window,'statechange',function(){ 
    // Note: We are using statechange instead of popstate 
    var State = History.getState(); 
    // Note: We are using History.getState() instead of event.state 
    History.log(State.data, State.title, State.url); 
}); 

而且還有Backbone.js,其中ma因爲它是一個MV *框架,但它具有路由器的概念,這也是有用的。

http://backbonejs.org/#Router

0

我想你可以檢查是否window.location.hash不是falsy值來檢查是否存在URL中的哈希值。

例如:

function someAlert(message) { 
    // This would be your alert function. This is just for example 
    alert(message); 
} 
// The "if the URL has a hash": 
if (window.location.hash) { 
    someAlert("Hello URL with a hash visitor!"); // "Hello URL with a hash visitor!" can be whatever you want 
} 

如果你想保存無論是後包括散列,只需使用:

var hash = window.location.hash; // hash would be "#login" if the URL was http://example.com/#login