【问题标题】:JS refresh while under a condition, stop when notJS在条件下刷新,不在时停止
【发布时间】:2014-02-26 04:45:23
【问题描述】:

我有一个页面,其中某些数据需要每分钟刷新一次,但用户需要查看/编辑某些模式(这些模式也需要刷新),所以当它们打开时,我想暂停数据刷新,因此在用户查看时模式不会消失。

我尝试了下面的代码,设置 var open_modal = false ,在打开一个modal时将其更改为true,这样setInterval方法就不会运行,然后在关闭时将其重置。模式打开或关闭时的代码正在运行,因为 alert(open_modal) 返回正确的值,但刷新继续发生。我假设在加载 dom 时正在运行 if 语句,但 if 语句没有重新运行,因此它无法识别更改。我尝试更改为 while 但页面不断刷新,用户无法在页面上执行任何操作。任何关于从这里去哪里的方向都将不胜感激。谢谢!

$(document).ready(function() {
  var open_modal = false;
  if (open_modal === false) {    // also tried while but the html continuously refreshes not allowing any use of the page
    $(function(){
      setInterval(function(){
        $('#trucks_refresh').click();
      },1000*60);
    });
  }
});

对于每个模态,打开时,将 open_modal 值重置为 true,然后在关闭时返回 false。

<script>
  $('#ticket_modal_<%= id %>').on('show', function () {
    var open_modal = true;
  });
  $('#ticket_modal_<%= id %>').on('hide', function () {
    var open_modal = false;
  });
</script>

【问题讨论】:

  • open_modal 回调中的 open_modal 变量与事件处理程序中的变量不同。如果要修改同一个变量,它必须与事件处理程序在同一范围内。

标签: javascript jquery ajax


【解决方案1】:

正如@Felix Kling 的评论中所指出的,您的显示/隐藏回调中的open_modal 与您在document.ready 回调中检查的不同,因为它们处于不同的执行范围(见下文) .

试试这个:

var myApp = {};

$(document).ready(function() {
  myApp.open_modal = false;
  if (myApp.open_modal === false) {    
    $(function(){
      setInterval(function(){
        $('#trucks_refresh').click();
      },1000*60);
    });
  }
});

后来:

<script>
  $('#ticket_modal_<%= id %>').on('show', function () {
    myApp.open_modal = true;
  });
  $('#ticket_modal_<%= id %>').on('hide', function () {
    myApp.open_modal = false;
  });
</script

以下是关于范围的几篇文章:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/ http://blog.kevinchisholm.com/javascript/scope/

来自第三个链接(由 Kevin Chisholm 提供):

month = 'july'; //global variable

function foo(){
    var month = "august"; //private
    console.log(month);
 };

console.log(month); //in the global scope, month = july

foo(); //in the local scope of the foo function, month = august

【讨论】:

  • 感谢@Will 的帮助!这有助于理解全局变量和私有变量。但是我已经对此进行了代码调整,并且当加载页面时 myApp.open_modal 返回正确的值,打开了一个模态,并关闭了一个模态。当模式打开且 myApp.open_modal = true 时,数据仍会刷新。是不是因为 if 语句只运行一次,就是第一次加载 dom,然后继续执行 setInterval 代码?
  • 我不太清楚你的问题。是的,if 条件只会在 dom 就绪时发生一次,是的,setInterval 循环将永远运行。根据您要执行的操作,您可能需要使用clearInterval,然后手动重新启动setInterval(可能使用on.('show') 回调)。 MDN info on clearInterval
  • 您准确地回答了我的问题。感谢您的提示。
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 2015-05-11
  • 2019-09-28
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
相关资源
最近更新 更多