【问题标题】:Reset a setInterval function with jquery使用 jquery 重置 setInterval 函数
【发布时间】:2011-12-23 23:27:08
【问题描述】:

这是我的代码:

$(document).ready(function() {
    $('#mid_select').live('click', function(e){ 
        $('#middle').load( $(this).attr('href') + ' #middle');
        var page =  $(this).attr("rel");
        alert(page);
        if (page == 'mywall'){
            var auto_refresh = setInterval(function () {
            $('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow");}, 5000); 
        } else {
            clearInterval(auto_refresh);     
        }
        e.preventDefault(); 
    }); 
});

我想要做的是,如果用户单击 id 为 #mid_selectrel 属性等于“mywall”的链接,则每 5 秒刷新一次 #bottom_middle div,但是如果用户单击rel 属性不等于“mypage”的链接,则不要每 5 秒刷新一次#bottom_middle div。还没有弄清楚如何完成这项工作,请帮助任何人?

【问题讨论】:

  • 在 jsfiddle 上发布您的 html。你不需要这部分:else { clearInterval(auto_refresh); }

标签: jquery html timer refresh


【解决方案1】:

您必须在点击处理程序外部存储对setIntervals 超时的引用(使用var)。此外,您必须确保一次最多有 一个 间隔循环。调整后的代码,如下所示,满足以下条件:

$(document).ready(function() {
    var auto_refresh = false;   // Store this variable OUTSIDE the click handler
    $('#mid_select').live('click', function(e){
        var $this = $(this);
        $('#middle').load( $this.attr('href') + ' #middle');
        var page =  $this.attr("rel");
        alert(page);
        if (page == 'mywall'){
            // Check whether an instance is already running...
            if (auto_refresh === false) {
                // NO var, because we use the auto_refresh var in the parent scope
                auto_refresh = setInterval(function () {
            $('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow");
                }, 5000); 
        } else {
            // Clear interval, and explicitly set it to true
            clearInterval(auto_refresh);
            auto_refresh = false;
        }
        e.preventDefault(); 
    }); 
});

【讨论】:

  • 是的,Rob,谢谢,效果很好!一件小事,不得不添加一个} 来结束if (auto_refresh === false) { 语句。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多