动态启动和停止计时事件

时间:2013-10-08 14:17:32

标签: jquery javascript-events setinterval

div 以下内容将附加到jquery弹出对话框中,并在对话框关闭时删除。

背后的想法是只需点击一下按钮即可切换自动刷新图表数据。

$('<div/>', {
    style: "position:absolute; top:39px; left:34px;z-index:1",
    click: function(){
        var imgSrc = $(this).find("img").attr('src');
        if(imgSrc=="images/green-circle.png"){
            imgSrc="images/black-circle.png";
            //how to stop calling the refresh function?  <--------------
        }
        else{
            imgSrc="images/green-circle.png";
            //Call refresh function every 60 sec
        }
        $(this).find("img").attr('src', imgSrc);
    }
    }).prepend('<img id="theImg"  width="20" height="20" src="images/black-circle-md.png" />').prependTo($(divHolder).parent());

以下是如何启动和停止计时器的示例:

var timer;

function startTimer() { 
    timer=setInterval(function(){refreshData()},1000);  
}

function stopTimer() { 
    learInterval(timer); 
}

refreshData(){
    // do some work here
}

截图

enter image description here

问题是,如何在timer函数内的点击之间保持对click: function(){} var的引用?因为可以有多个弹出对话框处于活动状态。对于不同的弹出对话框,应该可以独立刷新数据。

谢谢!

1 个答案:

答案 0 :(得分:1)

在事件处理函数中,您可以引用this中单击的特定元素,因此您应该能够将对计时器的引用存储为该元素的属性:

$('<div/>', {
    style: "position:absolute; top:39px; left:34px;z-index:1",
    click: function(){
        var imgSrc = $(this).find("img").attr('src');
        if(imgSrc=="images/green-circle.png"){
            imgSrc="images/black-circle.png";
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
        }
        else{
            imgSrc="images/green-circle.png";
            this.refreshTimer = setInterval((function() {
                 refreshData(this); // your refreshData function probably needs to know which div to refresh
            }).bind(this), 60000);
        }
        $(this).find("img").attr('src', imgSrc);
    }
})