有一种方法只有在给定的jsfiddle链接中单击按钮
后启动计时器var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
答案 0 :(得分:0)
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
答案 1 :(得分:0)
点击
后,您可以生成自定义事件 $(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
答案 2 :(得分:0)
请记住检查倒计时是否尚未开始。
$("button").click(function(){
});
这将为DOM中的所有按钮添加处理程序,然后只检查倒计时的状态。
答案 3 :(得分:0)
在click处理程序中有一个函数和一个变量,该变量表明函数是否已经启动。
此外,您可以在单个处理程序中添加点击事件,并且索引可以存储为data- *属性的一部分,从而减少重复的代码。
<强>的Javascript 强>
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
<强> HTML 强>
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
<强> Check Fiddle 强>