【问题标题】:How to refresh a page once using jQuery如何使用 jQuery 刷新页面一次
【发布时间】:2016-06-22 19:02:04
【问题描述】:

我想问你是否可以使用 jQuery 刷新一次页面。
如果哈希等于 add,下面的脚本将刷新页面。
我的目标是刷新一次相关页面。

 var url      = window.location.href; 
 var hash = url.substring(url.indexOf('#')+1);

 if(hash == 'add') {
 $(window).load(function(){

    location.reload();
});
}

【问题讨论】:

  • 除非您在重新加载时删除哈希,否则您的页面不会无限刷新吗?
  • 你可以使用setTimeout(function(){ //code here }, 2000)
  • 如果它不必是完全相同的 url,你可以添加一个查询参数,如果它不存在则只刷新。所以不要写location.reload(); location.href = location.href + "?foo=bar"

标签: javascript jquery


【解决方案1】:
var url     = window.location.href; 
var hash    = url.substring(url.indexOf('#')+1);
if(hash=='add') {
    window.location.href="#added";
}

您可以使用上面的代码来实现您的要求。 如果 #add 在 url 字符串中,它会使用新 url 重新加载一次,并附加 #added

【讨论】:

    【解决方案2】:

    你可以使用 cookie 这是一个例子

    function executeOnce () {
      var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string";
      if (bImplGlob) { argc++; }
      if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); }
      var fExec = arguments[0], sKey = arguments[argc - 2];
      if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); }
      if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); }
      if (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; }
      fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ? Array.prototype.slice.call(arguments, 2, argc - 2) : []);
      document.cookie = encodeURIComponent(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT" + (bImplGlob || !arguments[argc - 1] ? "; path=/" : "");
      return true;
    }
    

    用法
    executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, ...[, argumentToPassN]]​​]]], identifier[, onlyHere])

     function reloadPage () {
       var url      = window.location.href; 
       var hash = url.substring(url.indexOf('#')+1);
    
       if(hash == 'add') {
         $(window).load(function(){
          location.reload();
         });
       }
     }
    
    executeOnce(reloadPage, null, "", "idPage");
    

    【讨论】:

      【解决方案3】:

      这将重新加载页面。

      window.location.reload();

      你的意思是?

      var url = window.location.href; 
      var hash = url.substring(url.indexOf('#')+1);
      
      if(hash === 'add') {
          window.location.reload();
      }
      

      【讨论】:

      • 您好,感谢您的建议。我没有正确表达我的问题。我想刷新一次页面。有可能吗?
      猜你喜欢
      • 2011-07-21
      • 2011-01-02
      • 2012-05-09
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      相关资源
      最近更新 更多