[英]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.