gpt4 book ai didi

javascript - jquery 移动 + 间隔 : can't stop running in the background

转载 作者:行者123 更新时间:2023-11-30 05:51:15 26 4
gpt4 key购买 nike

我正在使用 jQuery Mobile,我只想有一个计数器来指示在页面上花费的时间。问题是,当用户没有看到页面时,我无法阻止计数器在后台增加。这是我的代码:

第 1 页

<!DOCTYPE html> 
<html>
<head>
<title>Page 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.js"></script>
<script>
$(document).bind("mobileinit", function(){
$.mobile.hashListeningEnabled = false;
});

var interval_id;

function checkEverySecond() {
$("#counter").html(parseInt($("#counter").html()) + 1);
};

$(document).bind("pageshow", function(){
interval_id = setInterval(function() {checkEverySecond()}, 1000);
});

$(document).bind("pagehide", function(){
clearInterval(interval_id);
});
</script>
</head>
<body>

<div data-role="page">

<div data-role="header">
<h1>Page 1</h1>
</div><!-- /header -->

<div data-role="content">
<p id="counter">0</p>
<a href="page2.html">Go to page 2</a>
</div><!-- /content -->

</div><!-- /page -->

</body>
</html>

第 2 页

<!DOCTYPE html> 
<html>
<head>
<title>Page 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.js"></script>
</head>
<body>

<div data-role="page">

<div data-role="header">
<h1>Page 2</h1>
</div><!-- /header -->

<div data-role="content">
<a href="page1.html">Go to page 1</a>
</div><!-- /content -->

</div><!-- /page -->

</body>
</html>

感谢您的帮助!

最佳答案

您将需要更改您的代码,jQm 页面事件的工作方式略有不同。您将页面事件绑定(bind)到每个页面,这是一个问题。您需要将它们绑定(bind)到一个页面。

这是一个工作示例:http://jsfiddle.net/Gajotres/DU493/

    var timerObject = {
interval_id : null
}

function checkEverySecond() {
$("#counter").html(parseInt($("#counter").html()) + 1);
};

$(document).on('pagebeforeshow', '#page1', function(){
timerObject.interval_id = setInterval(function() {checkEverySecond()}, 1000);
});

$(document).on('pagehide', '#page1', function(){
clearInterval(timerObject.interval_id);
});

我的示例是 1 个 html 多页模板,但同样的事情对多个 html 文件也适用。

编辑:

它在您的多 html 示例中不起作用的原因是因为使用了 bind 而不是 of on。还应在加载 jQuery Mobile 之前声明 mobileinit。

关于javascript - jquery 移动 + 间隔 : can't stop running in the background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14747935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com