只有在点击按钮后才能启动

时间:2014-02-28 19:47:18

标签: javascript jquery html

http://jsfiddle.net/Bwdfw/98/

有一种方法只有在给定的jsfiddle链接中单击按钮

后启动计时器

http://jsfiddle.net/Bwdfw/98/

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);
    }
}

4 个答案:

答案 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);
});

http://jsfiddle.net/Bwdfw/100/

答案 2 :(得分:0)

请记住检查倒计时是否尚未开始。

$("button").click(function(){

});

这将为DOM中的所有按钮添加处理程序,然后只检查倒计时的状态。

检查这个小提琴: http://jsfiddle.net/eddiarnoldo/Bwdfw/102/

答案 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