jQuery如何检测对网址的更改?
例如:如果用户转到页面site.com/faq/
没有显示任何内容,但如果他转到site.com/faq/#open
,则jquery会检测到并执行某些操作。
答案 0 :(得分:23)
试试这个
$(window).on('hashchange', function(e){
// Your Code goes here
});
它为我工作
答案 1 :(得分:22)
您可以使用 hashchange 事件。
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
}
window.addEventListener("hashchange", hashchanged, false);
$(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 :(得分:7)
只需在页面加载时查看window.location.hash
:
$(document).ready(function() {
if(window.location.hash === "open")
{
//Show something
}
});
或绑定到窗口的hashchange
事件:
$(document).ready(function() {
$(window).hashchange(hashchanged);
});
function hashchanged()
{
//Show something
}
答案 3 :(得分:2)
试试这个:
if (window.location.hash) {
// Fragment exists, do something with it
var fragment = window.location.hash;
}
仅供参考,#
指定的网址部分称为“片段”
答案 4 :(得分:1)
如果您的网址为site.com/faq/#open
,那么您可以
var hash = window.location.hash
获取hash = 'open'