jQuery 如何检测对 url 的更改?
例如:如果用户进入一个页面site.com/faq/什么都没有显示,但是如果他进入site.com/faq/#openjquery 会检测到它并做一些事情。
jQuery 如何检测对 url 的更改?
例如:如果用户进入一个页面site.com/faq/什么都没有显示,但是如果他进入site.com/faq/#openjquery 会检测到它并做一些事情。
试试这个
$(window).on('hashchange', function(e){
 // Your Code goes here
});
它对我有用
您可以使用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.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 部分#称为“片段”
如果你有一个 url site.com/faq/#open,那么你可以做
var hash = window.location.hash
要得到 hash = 'open'