如何让jquery反复运行

how to get jquery to run repeatedly

本文关键字:运行 jquery      更新时间:2023-09-26

我目前有一段jquery代码,它查找特定的URL(在末尾有一个锚),并在匹配时运行一个函数。如果这是加载的第一个URL,则代码只运行一次。是否有可能让以下代码运行,直到它有一个匹配?

$(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(); 
        }
    })
});

它只运行第一次,因为更改哈希不会再次触发DOM就绪处理程序,但它会触发hashchange事件。

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

注意,window总是可用的,并且不需要DOM就绪处理程序

您可以使用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();
});

但是你的代码背后的想法是什么?我相信有更方便的方法来完成你的任务。

使用adeneo的答案:

下面是与你的代码匹配的内容:

$(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();
        }
   });
});