2012-08-06 54 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

相關問題