2014-02-06 71 views
0

我正在使用計時器,當我點擊按鈕時,計時器從5秒開始,當它涉及到0時淡出。我試過但沒有得到,這裏是我試過的小提琴:http://jsfiddle.net/GNrUM/937/問題與jQuery倒計時計時器

<div id="hideMsg" style="display:none;"> 
This Box will Close In <span>5</span> Seconds..</div> 
<input id="take" type="button" value="click me" > 

jQuery代碼:

$("#take").live("click", function() { 
    $('#hideMsg').show(); 
    var sec = $('#hideMsg span').text() 
    var timer = setInterval(function() { 
     $('#hideMsg span').text(--sec); 
     if (sec == 0) { 
      $('#hideMsg').fadeOut('fast'); 
      clearInterval(timer); 
     } 
    }, 1000); 
}); 

它的工作好第一次點擊,當點擊2次計數從0開始,-1,-2,。它沒有清除間隔。任何幫助?

+0

嘗試重新初始化'$( '#hideMsg跨度')'。 like'$('#hideMsg span')。text('5');' http://jsfiddle.net/GNrUM/941/ –

+0

謝謝你的工作:) – honey

+0

繼續.. njoy :) –

回答

0

試試這個:

$("#take").live("click",function(){ 
    $('#hideMsg').show();  
    var sec = $('#hideMsg span').text() 
    var timer = setInterval(function() { 
     $('#hideMsg span').text(--sec); 
     if (sec == 0) { 
      $('#hideMsg').fadeOut('fast'); 
      $('#hideMsg span').text("5"); // reinitialize the span value 
      clearInterval(timer); 
     } 
    }, 1000); 
    }); 
+0

更好在淡出的回調方法中做。如'$('#hideMsg')。fadeOut('fast',function(){('#hideMsg span').text(5); });'' – Satpal

1

你一旦淡出

$('#hideMsg span').text(5); 

JS小提琴演示demo