Javascript 如何使用 jQuery 检测 URL 更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8212845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect URL changes with jQuery
提问by skywind
How can jQuery detect changes to a url?
jQuery 如何检测对 url 的更改?
For example: If a user goes to a page site.com/faq/
nothing shows, but if he goes to site.com/faq/#open
jquery detects it and does something.
例如:如果用户进入一个页面site.com/faq/
什么都没有显示,但是如果他进入site.com/faq/#open
jquery 会检测到它并做一些事情。
回答by user3354817
Try This
尝试这个
$(window).on('hashchange', function(e){
// Your Code goes here
});
Its working for me
它为我工作
回答by UnLoCo
You can use the hashchangeevent.
您可以使用hashchange事件。
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
}
window.addEventListener("hashchange", hashchanged, false);
or integrate a jquery hashchange plugin
或者集成一个jquery hashchange 插件
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
}
回答by James Hill
Simply look at window.location.hash
on page load:
只需查看window.location.hash
页面加载:
$(document).ready(function() {
if(window.location.hash === "open")
{
//Show something
}
});
Or bind to the hashchange
event of the window:
或者绑定到hashchange
窗口的事件:
$(document).ready(function() {
$(window).hashchange(hashchanged);
});
function hashchanged()
{
//Show something
}
回答by Rory McCrossan
Try this:
尝试这个:
if (window.location.hash) {
// Fragment exists, do something with it
var fragment = window.location.hash;
}
Just for reference, the part of a url specified by the #
is called a 'fragment'
仅供参考,由 指定的 url 部分#
称为“片段”
回答by Utku Y?ld?r?m
If you have a url of site.com/faq/#open
, then you can do
如果你有一个 url site.com/faq/#open
,那么你可以做
var hash = window.location.hash
to get hash = 'open'
要得到 hash = 'open'