简体   繁体   English

如何让jQuery重复运行

[英]how to get jquery to run repeatedly

I currently have a piece of jquery code that looks for a specific URL (with an anchor at the end) and runs a function if it has a match. 我目前有一段jquery代码,用于查找特定的URL(末尾带有锚),并在有匹配项时运行一个函数。 The code only runs once, if this is the first URL loaded. 如果这是第一个加载的URL,则该代码仅运行一次。 Is it possible to have the following code running until it has a match? 是否可以运行以下代码,直到匹配为止?

$(document).ready(function(){
   var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
   $(function(){
        if (location.href==url){
            paintLine(); 
        }
    })
});

It only runs the first time, because changing the hash does not fire the DOM ready handler again, it does however fire the hashchange event. 它仅在第一次运行,因为更改哈希不会再次触发DOM ready处理程序,但是会触发hashchange事件。

$(window).on('hashchange', function() {
    if ( window.location.hash === '#backup-section-3' ) {
        paintLine();
    }
}).trigger('hashchange'); // fire on first load as well

Note that the window is always available, and does not need a DOM ready handler 请注意,该window始终可用,并且不需要DOM ready处理程序

you can use setTimeout() function to run your function, for example every second: 您可以使用setTimeout()函数运行函数,例如每秒运行一次:

$(document).ready(function(){
   var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";

   function test() {
      if (location.href == url) {
         paintLine();
      } else {
         setTimeout(test, 1000);
      }
   }
   test();
});

but what is your idea, behind your code? 但是您的想法是什么,在代码的背后? I sure there is more convenient ways to do your task. 我确定有更方便的方法来完成您的任务。

using adeneo's answer: 使用adeneo的答案:

here is what matches your code: 这是与您的代码匹配的内容:

$(document).ready(function(){
   var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
   $(function(){
        if (location.href==url){
            paintLine(); 
        }
    });
   $(window).on('hashchange', function() {
        if ( location.href == url ) {
            paintLine();
        }
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM