[英]How to get my javascript function to start on element click?
我的代码如下,但是它似乎是在页面加载时立即启动的,当我希望单击某个元素时启动它。 不确定为什么在页面加载时触发?
计时器过去后,该代码从视图中删除了“下一个问题”和“上一个问题”元素,因此用户必须结束测验。
理论上,要单击的元素(例如#pretest)应同时消失并启动计时器,但是我尝试的每种方法都会中断计时器或计时器完全忽略该规则。
JS新手总数。
$(function() {
$('#next-question,#prev-question').removeAttr('disabled');
setTimeout(enableButton, 678000);
function enableButton(){
$('#next-question,#prev-question').css( 'display', 'none' );
$('#next-question,#prev-question').attr("disabled", "false");
}
});
function countdown() {
var m = $('.min');
var s = $('.sec');
if(m.length == 0 && parseInt(s.html()) <= 0) {
$('.displayCounter_ng').html('Test Complete');
}
if(parseInt(s.html()) <= 0) {
m.html(parseInt(m.html()-1));
s.html(60);
}
if(parseInt(m.html()) <= 0) {
$('.displayCounter_ng').html('<span class="sec">59</span> seconds');
}
s.html(parseInt(s.html()-1));
}
setInterval('countdown()',1000);
您的函数正在页面加载时运行,因为您有
setInterval('countdown()',1000);
在您的函数定义之后。 这意味着浏览器每隔1000毫秒(每秒)执行一次countdown()代码。 相反,您可以像这样设置它并运行onclick进行任何#pretest测试
<html>
<head>
<script type="text/javascript" src="js/counter.js"></script>
<head>
<body>
<button id="pretest" onclick="countdown()">Click to start test</button>
</body>
</html>
function countdown() {
setInterval(function() {
// ... Countdown code here
}, 1000);
}
就像Barmar和Cracker0dks所说的那样,setInterval在页面加载后立即触发,因此您应该将其放入onclick侦听器中。 与jQuery的是
$('#pretest').click(function(){
id = setInterval(function(){countdown();}, 1000); //you'll need the id later
});
请注意,您要保留从setInterval返回的结果,因为完成该过程后将需要它来清除时间间隔。
由于您想在单击按钮后立即隐藏执行某些操作,即隐藏按钮,因此应将其添加到onclick侦听器中,这样它就成为
$('#pretest').click(function(){
//Hide elements here
$('#next-question,#prev-question').hide();
id = setInterval(function(){countdown();}, 1000);
});
似乎您也希望计时器操作在时间为零时结束并启用一些按钮,因此您需要编辑倒数计时功能以清除计时器并在时间为零时显示按钮,因此它应变为:
function countdown() {
var m = $('.min');
var s = $('.sec');
if(m.length == 0 && parseInt(s.html()) <= 0) {
window.clearInterval(id);
enableButton();
$('.displayCounter_ng').html('Test Complete');
}
if(parseInt(s.html()) <= 0) {
m.html(parseInt(m.html()-1));
s.html(60);
}
if(parseInt(m.html()) <= 0) {
$('.displayCounter_ng').html('<span class="sec">59</span> seconds');
}
s.html(parseInt(s.html()-1));
}
这是小提琴的链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.