我正在尝试制作倒计时时钟,当用户点击按钮时,它会启动计时器.但是,现在,只要页面加载,倒计时就会开始.我怎么能等到用户真正按下id='startCountdown'
按钮才能启动countdown
.我是JavaScript新手,非常感谢一些反馈.
.js代码:
// Wait for webpage to load $(document).ready(function(){ var sessionTime = 1; var breakTime = 5; // Update session and break times with pre-defined variables $('#session-time').text(sessionTime); $('#rest-time').text(breakTime); // jQuery click functions for increasing and decreasing time $('#decrease-session').on('click', downSession); $('#increase-session').on('click', upSession); $('#decrease-rest').on('click', downBreak); $('#increase-rest').on('click', upBreak); // Decrease the length of each session function downSession() { sessionTime--; $('#session-time').text(sessionTime); $('#countdown-time').text(sessionTime); } // Increase the length of each session function upSession() { sessionTime++; $('#session-time').text(sessionTime); $('#countdown-time').text(sessionTime); } // Decrease the length of each break function downBreak() { breakTime--; $('#rest-time').text(breakTime); } // Increase the length of each break function upBreak() { breakTime++; $('#rest-time').text(breakTime); } // Convert session and break times to seconds var sessionConverted = sessionTime * 60; var breakConverted = breakTime * 60; // When clicked, send to start countdown $('#startCountdown').on('click', countdown(sessionConverted)); // Convert time and return in H:M:S function convertTime(time) { time = parseInt(time, 10); var hours = Math.floor(time / 3600); var minutes = Math.floor((time % 3600) / 60); var seconds = Math.floor((time % 3600) % 60); return { 'H': hours, 'M': minutes, 'S': seconds }; } // Interval function that will decrement the time function countdown(count) { var timerId = setInterval(function() { // Decrement the count count--; // Send count to convertTime to display var t = convertTime(count); var hours = 0; var mins = 0; var secs = 0; // If statements to check if time is less than 10 // If so, add leading "0" (t['H'] < 10) ? (hours = "0" + t['H']) : (hours = t['H']); (t['M'] < 10) ? (mins = "0" + t['M']) : (mins = t['M']); (t['S'] < 10) ? (secs = "0" + t['S']) : (secs = t['S']); if (hours >= 1) { $('#countdown-time').text(hours + ":" + mins + ":" + secs); } else { $('#countdown-time').text(mins + ":" + secs); } // Stop counting if the count has reached "0" if(count < 1) { clearInterval(timerId); } }, 1000); } });
用于测试的Codepen:
http://codepen.io/Mukul215/pen/obxLev
您正在立即调用该countdown
函数,而不是将其.on
作为处理程序提供.
$('#startCountdown').on('click', countdown(sessionConverted));
因为在表达式中使用括号,所以countdown(sessionConverted)
会立即调用并返回值作为.on
方法的处理程序.并且因为返回值不是函数,所以click事件实际上并没有做任何事情.
试试这个:
$('#startCountdown').on('click', function (e) { countdown(sessionConverted); });