所以,我的问题是,当我点击“后退”图标时,我正试图让我的倒计时清除。这样,如果用户点击返回计时器页面,它将被重置,而不是从他们回击时继续。
这是我认为应该做的诀窍代码:
$('.ui-icon-back').click (clearInterval(countdown));
这是我的HTML:
<!-- /////////////////
Green Tea
////////////////////// -->
<!--Create section tag-->
<section data-role="page" id="green">
<!--Create header tag-->
<header data-role="header">
<!--Create h1 tag-->
<h1> TEA TIME </h1>
<!--Create a icon that will link back to the home page-->
<a href="#home" class="ui-btn ui-btn-icon-top ui-icon-back ui-btn-icon-notext">back</a>
<!--End header-->
</header>
<!--Create h1 tag that states full steep time-->
<h1>Green Tea Takes 2 Minutes</h1>
<!--Show timer duration before timer start-->
<p id="timedisp">120 sec</p>
<!--Call the countdown-->
<div class="clock">
</div>
<!-- Button to trigger the start timer js-->
<a href="#" id="start">Start</a>
<!-- Button to trigger the timer restart-->
<a href="#" id="reset">Reset</a>
<!-- End section tag-->
</section>
这是我的Javascript:
// JavaScript Document
//Green Tea Timer
function greenTea(){
// Set The Duration
var duration = 120;
// Insert the duration into the div with a class of clock
$(".clock").html(duration + " sec");
// Create a countdown interval
var countdown = setInterval(function (greenTea) {
// subtract one from duration and test to see
// if duration is still above zero
if (--duration) {
// Update the clocks's message
$(".clock").html(duration + " sec");
// Otherwise
} else {
// Clear the countdown interval
clearInterval(countdown);
// set a completed message
$(".clock").html("End Your Steep");
}
// Run interval every 1000ms
}, 1000);
};
$("a#start").click(greenTea);
$('#start').click(function(greenTea){
$('#timedisp').hide();
});
$('#reset').click(function(greenTea) {
location.reload();
});
$('.ui-icon-back').click (clearInterval(countdown));
答案 0 :(得分:0)
当你这样做时:
$(..).click(clearInterval(..));
JavaScript立即执行clearInterval方法。你需要这样做:
$(..).click(function(){
clearInterval(..);
});
之后,您需要将该代码放在greenTea函数中,以便clearInterval能够访问countdown
变量。那或在greanTea之外声明变量countdown
。我建议做第一个,因为第二个会污染全球范围。
答案 1 :(得分:0)
countdown
变量在greenTea
函数内声明。您必须在函数外部声明它才能从单击处理程序访问它。
您还必须将jQuery函数放在jQuery ready函数中:
var countdown;
function greenTea(){
var duration = 120;
$(".clock").html(duration + " sec");
countdown = setInterval(function (greenTea) {
if (--duration) {
$(".clock").html(duration + " sec");
} else {
clearInterval(countdown);
$(".clock").html("End Your Steep");
}
}, 1000);
};
$(function(){
$("a#start").click(greenTea);
$('#start').click(function(greenTea){
$('#timedisp').hide();
});
$('#reset').click(function(greenTea) {
location.reload();
});
$('.ui-icon-back').click (function(){
clearInterval(countdown));
});
});