每次我的URL更改时如何重新加载JQuery?

时间:2016-06-29 15:33:44

标签: jquery

每次更改URL时如何调用此函数?

$(document).ready(function() {
  console.log("URL change!");
});

我尝试了类似的东西,但它不起作用:

$(window).on('hashchange', function(e){
  $(document).ready(function() {
    console.log("URL change!");
  });
});

2 个答案:

答案 0 :(得分:1)

您需要在Cookie中保存“旧”网址:

$(document).ready(function() {
  // read old saved URL
  var oldURL = $.cookie("oldURL");

  // check for URL change
  if (oldURL != window.location.href) {
    console.log("URL change!");
  }

  // save current URL in cookie
  $.cookie("oldURL", window.location.href);
});

唯一的问题是,在第一次调用时,cookie是空的,因此URL更改也会在第一次调用时发生。

答案 1 :(得分:0)

如果您需要从您可以执行的网址获取哈希

$(document).ready(function(){
    var hash = window.location.hash;

     //Some condition
     if(hash=="foo"){
        //hash is foo do something

     }else if(hash=="bar"){
        //hash is bar do something

     }else{
        //hash is not foo nor bar : do something
     }
    console.log(hash);
});

如果您需要获取完整网址,请使用window.location.href代替

$(document).ready(function(){
    var url = window.location.href;
    console.log(url);
});

现在,如果你想检查hashchange事件,你可以使用以下内容,尽管hashchange适用于jQuery mobile

 $( window ).hashchange(function() {
    var hash = location.hash;
    console.log(hash);
 });

$( window ).hashchange();

如果您想跟踪上一个网址,可能需要使用cookie

关于你的问题每次我的网页更改时如何重新加载JQuery?每次加载页面时都会重新加载jQuery,所以如果你只想知道网址中的哈希并用哈希值做一些东西我的第一个例子将完成这项工作:)

相关问题