如何使用jQuery检测URL更改

时间:2011-11-21 13:48:57

标签: javascript jquery url

jQuery如何检测对网址的更改?

例如:如果用户转到页面site.com/faq/没有显示任何内容,但如果他转到site.com/faq/#open,则jquery会检测到并执行某些操作。

5 个答案:

答案 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);

或整合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 :(得分: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'