所有页面上的Javascript全局数组均为空

时间:2019-06-21 17:44:21

标签: javascript arrays global

在我网站的一页上,创建了计时器。我需要能够访问其他页面上的计时器以查看剩余时间。但是我无法使全局数组正常工作。

在网站的开头,我创建了all_timers数组(如果为空)。然后在计时器函数中,将计时器的ID推入该数组。但是当我重新加载页面时,数组始终为空。

运行“计时器”页面时,控制台显示“已按下”。但是只要页面更新,它就会显示“ create new”。

我对使用窗口感到困惑。有些帖子说要使用它,有些没有提到它,有的表明它用于变量的所有实例,而不仅是在创建变量时。 Sp我是否错误地创建了全局?尽管我尝试了许多变体,但我只是在这里显示了基本用法。有人可以指出我所缺少的吗?请注意,这是简化的代码。实际上确实调用了timer函数。

    <head>

    <script> 
    if (typeof all_timers !== 'undefined' && all_timers.length > 0) {
      console.log('found '+all_timers.length);
      for (var i = 0; i < all_timers.length; i++) {
        console.log('main timer '+all_timers[i]);
      }    
    } else {
      console.log('create new');
      window.all_timers = new Array();
    }
    </script>

    </head>
    <body>


    <script>
    function createfunc(idx) {
        if ($("#time-left-"+idx).length === 0) {
          clearInterval(timerID[idx]);
        } else { 
          timerID[idx] = setInterval(function() {
            if (show_timer > 0) {
              all_timers.push('some thing'+idx);
              console.log('pushed');
            } else {
              clearInterval(timerID[idx]);
            }   
          }, 1000);
        }    
    }
    </script>
    </body>

1 个答案:

答案 0 :(得分:2)

您将需要使用local storage保存全局时间戳,或者将时间戳作为URL parameter传递。

无论您使用本地存储还是url参数,您都只能在页面之间传递字符串。

相关问题