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