2013-03-25 26 views
2

我希望alertMe函數僅在單擊該按鈕時被調用,但會被調用(setInterval被調用哪個調用該函數)就像頁面加載一樣。但是如果我把pageLoad函數帶走,那麼startButton就是null,我不能用它做任何事情。提前感謝,夥計們!setInterval()如何處理button.onclick

/when user clicks start, start the animation 
window.onload = pageLoad; 

function pageLoad() { 
    var startButton = document.getElementById("start"); 

    startButton.onclick = setInterval(alertMe,200); 
} 

function alertMe() { 
    alert("hi"); 
} 

回答

5
function pageLoad() { 
    var startButton = document.getElementById("start"); 

    startButton.onclick = alertMe; 
} 

function alertMe() { 
    setInterval(function(){ 
    alert("hi"); 
    },200); 
} 

移動你的間隔alertMe函數內部,並傳遞作爲參考,startButton.onclick

DEMO:http://jsfiddle.net/gHS4a/

+0

按鈕被點擊。 – 2013-03-25 02:13:19

+0

是不是說「onlick」函數表示按鈕已被點擊? – 2013-03-25 02:15:22

+0

正確,但它被分配給您的語句的返回值,而不是它可以執行的函數。 – ahren 2013-03-25 02:23:15

3

基本上你需要做的是這樣的:

startButton.onclick = function() { 
    interval = setInterval(alertMe, 200); 
} 

它做的是發送引用NCE到alertMe功能

另一種方法是:

startButton.onclick = function() { 
    interval = setInterval(function(){ 
     alertMe(); 
    }, 200); 
} 

這將發送到一個匿名函數的引用因爲你希望它以後*的啓動循環*,它會調用alertMe功能