单击div后启动功能

时间:2014-03-08 03:29:59

标签: javascript jquery function html

我有一个div元素和一个timer函数,如下所示。

单击div后如何启动该功能?

<div id="link"></div>

<script type="text/javascript">
    var obj = document.getElementById('link');
    var timerFIG = 7;
    var timer = setInterval("startTimer()",1000);
    function startTimer() {
        if(timerFIG !== 1) {
            timerFIG--;
        } else {
            clearInterval(timer);
            obj.innerHTML = '<img src="/button.png" border="0" />';
        }
    }
</script>

2 个答案:

答案 0 :(得分:0)

使用jQuery

//dom ready handler
jQuery(function ($) {
    var $obj = $('#link');
    var timerFIG = 7;
    var timer;

    //click handler for the link
    $obj.click(function () {
        timer = setInterval(startTimer, 1000);
    })

    function startTimer() {
        if (timerFIG !== 1) {
            timerFIG--;
        } else {
            clearInterval(timer);
            $obj.html('<img src="/button.png" border="0" />');
        }
    }
})

演示:Fiddle

答案 1 :(得分:0)

试试这个

<div id="link">7</div>

<input type="button" value="Start"  onclick="startcounting();"/>


<script type="text/javascript">
    var obj = document.getElementById('link');
    var timerFIG = 7;

    function startcounting()
    {
      var timer = setInterval(function(){

            if(timerFIG != 1) {
                         timerFIG--;
                         obj.innerHTML = timerFIG;
                  } else {
                   clearInterval(timer);
                   obj.innerHTML = '<img src="/button.png" border="0" />';
               }

         },1000);
    }
</script>