2011-11-21 109 views
21

jQuery如何检测URL的更改?如何使用jQuery检测URL更改

例如:如果用户转到页面site.com/faq/什么也没有显示,但如果他去site.com/faq/#open jquery检测到它并执行某些操作。

+1

你应该看看[jQuery的地址插件(HTTP://www.asual。 com/jquery/address /) –

+2

@Sahil我假设他希望这样,以便他可以在页面加载时使用它,例如打开选项卡控件中的特定选项卡。知道这是一个方便的技术。 –

回答

2

试试这个:

if (window.location.hash) { 
    // Fragment exists, do something with it 
    var fragment = window.location.hash; 
} 

仅供参考,由#指定的URL的一部分,被称为“片断”

1

如果你有site.com/faq/#open一个URL,那么你可以做

var hash = window.location.hash 

得到hash = 'open'

6

单纯看window.location.hash在页面加载:

$(document).ready(function() { 
    if(window.location.hash === "open") 
    { 
     //Show something 
    } 
}); 

或绑定到hashchange事件窗口:

$(document).ready(function() { 
    $(window).hashchange(hashchanged); 
}); 

function hashchanged() 
{ 
    //Show something 
} 
20

可以使用hashchange事件。
或集成jquery hashchange plugin

$(function(){ 

    // Bind the event. 
    $(window).hashchange(hashchanged); 

    // Trigger the event (useful on page load). 
    hashchanged(); 

}); 

function hashchanged(){ 
var hash = location.hash.replace(/^#/, ''); 
//your code 
} 
+2

另请参阅[jQuery BBQ插件](http://benalman.com/projects/jquery-bbq-plugin/),虽然这可能比OP要求更复杂。 – Blazemonger

+1

没有像$(window).haschange这样的事情,而问题是关于检测URL变化没有改变。 – OviC

+0

'$(window).haschange'属于上面提到的插件,用OP – UnLoCo

18

尝试这个

$(window).on('hashchange', function(e){ 
// Your Code goes here 
}); 

它的工作对我来说