2012-08-06 56 views
2

我正在放置一个包含用于webcams的几个单独页面(* .htm)的jquery移动网站。在这些页面上,我加载了一个设置间隔功能,每隔几秒刷新一次摄像头的图像并模拟视频。当在jquery mobile中离开页面时结束SetInterval函数

但是,当我使用导航链接或返回按钮返回到index.htm远离网络摄像头页面(webcam.htm)时,会出现问题,webcam.htm页面仍保留在DOM中并且每隔几个小时不断拉动图像秒。

如何在用户离开时清除页面或至少结束间隔?

<script type="text/javascript"> 
    function camfresh() { 
     setInterval(function(){ $("#rmcam").attr("src", "image.jpg?"+new Date().getTime());},2000); 
    } 
</script> 
+0

如果你不想搞乱听众,可以通过一个快速而肮脏的解决方案来清除间隔内的时间间隔(如果这种情况发生,在这种情况下,如果页面不再可见)。可见性问题见http://stackoverflow.com/questions/178325/testing-if-something-is-hidden-with-jquery)。 – reallynice 2013-11-28 12:39:22

回答

2

您可以使用pageshowpagehide事件来启动和停止的时间间隔:

var myInterval; 
$(document).delegate('.ui-page', 'pageshow', function() { 

    //note that `this` refers to the current `data-role="page"` element 

    //cache `this` for later (inside the setInterval anonymous function) 
    var $this = $(this); 

    myInterval = setInterval(function(){ 
     $this.find("#rmcam").attr("src", "image.jpg?"+new Date().getTime()); 
    }, 2000); 
}).delegate('.ui-page', 'pagehide', function() { 
    clearInterval(myInterval); 
}); 

您可以更改.ui-page选择更具体的(目前,他们将选择每个伪页)。

+0

感谢您的协助,看起来像间隔是加载和触发,但我越来越TypeError:$ this.find不是一个函数 [Break On This Error] \t $ this.find(“#rvcam”)。attr (“src”,“image.jpg?”+ new Date()。getTime()); #webcams(线19) 类型错误:$ this.find不是函数 [打破该误差] \t $ this.find( “#rvcam”)ATTR( “SRC”,“图像。 jpg?“+ new Date()。getTime());有任何想法吗? – edvan22 2012-08-09 09:44:24

+0

是的,'.find()'是一个必须在jQuery对象上运行的方法,因为它是一个jQuery函数。我只缓存'this'而不是'$(this)'。我用这个修补程序编辑了这个问题。 – Jasper 2012-08-09 16:26:42

+0

谢谢贾斯珀 - 终于得到了这个工作! – edvan22 2012-09-02 12:17:04

相关问题