JS在条件下刷新,不在时停止

时间:2014-02-26 04:45:24

标签: javascript jquery ajax

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

我尝试了以下代码,设置var open_modal = false,在打开模式时将其更改为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>

1 个答案:

答案 0 :(得分:0)

正如@Felix Kling的评论中所述,您的show / hide回调中的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